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?
You can now write hideKeyboard() from inside any SwiftUI view. Important: If you're using Xcode 12 you need to use RoundedBorderTextFieldStyle() rather than . roundedBorder .
Via Tap Gesture This is the quickest way to implement keyboard dismissal. Just set a Tap gesture on the main View and hook that gesture with a function which calls view. endEditing . Causes the view (or one of its embedded text fields) to resign the first responder status.
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.
Swift 5 helper function
func dismissKeyboardIfPresent() { if app.keyboards.element(boundBy: 0).exists { if UIDevice.current.userInterfaceIdiom == .pad { app.keyboards.buttons["Hide keyboard"].tap() } else { app.toolbars.buttons["Done"].tap() } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With