How to hide keyboard in Swift app during UI testing

leizeQ picture leizeQ · Dec 3, 2015 · Viewed 17.4k times · Source

I just started with UI testing in Xcode 7 and hit this problem:

I need to enter text into a textfield and then click a button. Unfortunately this button is hidden behind the keyboard which appeared while entering text into the textfield. Xcode is trying to scroll to make it visible but my view isn't scrollable so it fails.

My current solution is this:

let textField = app.textFields["placeholder"]
textField.tap()
textField.typeText("my text")
app.childrenMatchingType(.Window).elementBoundByIndex(0).tap() // hide keyboard
app.buttons["hidden button"].tap()

I can do this because my ViewController is intercepting touches:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    view.endEditing(false)
    super.touchesBegan(touches, withEvent: event)
}

I am not really happy about my solution, is there any other way how to hide the keyboard during UI testing?

Answer

bbjay picture bbjay · Aug 8, 2016

If you have set up your text fields to resign FirstResponder (either via textField.resignFirstResponder() or self.view.endEditing(true)) in the textFieldShouldReturn() delegate method, then

textField.typeText("\n")

will do it.