How to hide keyboard in Swift app during UI testing How to hide keyboard in Swift app during UI testing ios ios

How to hide keyboard in Swift app during UI testing


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.


Based on a question to Joe's blog, I have an issue in which after a few runs on simulator the keyboards fails to hide using this piece of code:

XCUIApplication().keyboard.buttons["Hide keyboard"]

So, I changed it to: (thanks Joe)

XCUIApplication().keyboard.buttons["Hide keyboard"]let firstKey = XCUIApplication().keys.elementBoundByIndex(0)if firstKey.exists {   app.typeText("\n")}

What I try to do here is detecting if the keyboard stills open after tap the hide button, if it is up, I type a "\n", which in my case closes the keyboard too.

This also happens to be tricky, because sometimes the simulator lost the focus of the keyboard typing and this might make the test fail, but in my experience the failure rate is lower than the other approaches I've taken.

I hope this can help.


XCUIApplication().toolbars.buttons["Done"].tap()