Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide keyboard in Swift app during UI testing

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?

like image 967
leizeQ Avatar asked Dec 03 '15 10:12

leizeQ


People also ask

How do I hide the keyboard in SwiftUI?

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 .

How do I turn off keyboard Swift?

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.


2 Answers

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.

like image 199
bbjay Avatar answered Sep 28 '22 03:09

bbjay


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()         }     } } 
like image 22
trishcode Avatar answered Sep 28 '22 03:09

trishcode