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

时间:2016-01-08 19:43:31

标签: ios iphone xcode swift uitest

我正在新的Xcode 7 UI测试框架下用swift编写UI文本。 要求是测试系统键盘是否显示在应用程序中。 谁能给我一个如何做到的线索?感谢

3 个答案:

答案 0 :(得分:17)

尝试此检查:

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 :(得分:1)

添加两名观察员

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

答案 2 :(得分:0)

我发现键盘计数检查在我的一个应用程序上不起作用(即使隐藏了键盘,键盘计数检查仍返回1),因此请对其稍做修改:

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