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

how to Detect if Keyboard is shown in Xcode UI test

我正在 swift 中使用新的 Xcode 7 UI 测试框架编写 UI 文本。 要求是测试系统键盘是否显示在应用程序中。 有人可以告诉我该怎么做吗?谢谢

添加两个观察者

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")
}

只要键盘可见,就会调用 keyboardVisible,只要键盘隐藏,就会调用 keyboardHidden

试试这个检查:

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

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

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

您还可以通过键盘控制交互:

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

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

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