如何检测键盘是否显示在 Xcode UI 测试中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34684846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:24:14  来源:igfitidea点击:

how to Detect if Keyboard is shown in Xcode UI test

iosiphonexcodeswiftuitest

提问by user2823793

I am writing a UI text in swift under the new Xcode 7 UI test framework. the requirement is to test whether the system keyboard is shown in an app. can someone give me a clue on how to do that? thanks

我正在新的 Xcode 7 UI 测试框架下快速编写 UI 文本。要求是测试系统键盘是否显示在应用程序中。有人可以给我一个关于如何做到这一点的线索吗?谢谢

采纳答案by Rashwan L

Add two observers

添加两个观察者

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardVisible:", name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardHidden:", name: UIKeyboardDidHideNotification, object: nil)

func keyboardVisible(notif: NSNotification) {
    print("keyboardVisible")
}

func keyboardHidden(notif: NSNotification) {
    print("keyboardHidden")
}

Whenever the keyboard is visible keyboardVisiblewill be called and whenever the keyboard is hidden keyboardHiddenwill be called.

每当键盘可见时keyboardVisible将被调用,每当键盘隐藏时keyboardHidden将被调用。

回答by JoriDor

Try this check:

试试这个检查:

let app = XCUIApplication()
XCTAssert(app.keyboards.count > 0, "The keyboard is not shown")

Or check for specific keyboard keys like:

或检查特定的键盘键,如:

let app = XCUIApplication()
XCTAssert(app.keyboards.buttons["Next:"].exists, "The keyboard has no Next button")

You can also control interactions on the keyboard:

您还可以控制键盘上的交互:

let app = XCUIApplication()
app.keyboards.buttons["Next:"].tap()

回答by Charlie Seligman

I found the keyboard count check didnt work on one of my apps (it returned a count of 1 even when the keyboard was hidden), so amended it slightly:

我发现键盘计数检查在我的一个应用程序上不起作用(即使键盘隐藏,它返回的计数也是 1),所以稍微修改了一下:

private fund isKeyboardShown() -> Bool {
    return XCUIApplication().keyboards.keys.count > 0
}