简体   繁体   English

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

[英]how to Detect if Keyboard is shown in Xcode UI test

I am writing a UI text in swift under the new Xcode 7 UI test framework.我正在新的 Xcode 7 UI 测试框架下快速编写 UI 文本。 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谢谢

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()

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 keyboardVisible will be called and whenever the keyboard is hidden keyboardHidden will be called.每当键盘可见时, keyboardVisible将被调用,而当键盘隐藏时, keyboardHidden将被调用。

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 func isKeyboardShown() -> Bool {
    return XCUIApplication().keyboards.keys.count > 0
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM