Search code examples
iosswiftuitextfieldbecomefirstresponder

iOS (Swift): UITextField is **not** first responder after becomeFirstResponder method is called?


I have an array of UITextFields inside a UIViewController:

@IBOutlet weak var textField1: UITextField!
@IBOutlet weak var textField2: UITextField!
var textFields: [UITextField] {
    return [textField1, textField2]
}

In my viewDidLoad method, I set the first element of the textFields array to be the first responder and set all of their delegates as follows:

override func viewDidLoad() {
    super.viewDidLoad()

    textFields[0].becomeFirstResponder()
    textFields.forEach({ $0.delegate = self })

    print(textFields.map({ $0.isFirstResponder })) // [false, false]

}

However, the print statement in the viewDidLoad prints [false, false] rather than [true, false] as I might have expected. Why?

Thanks


Solution

  • You're running this code too soon. No text field can become first responder during viewDidLoad, because no text field is even in the interface yet.

    To put it another way, try changing your code to:

    print(textFields.map({ $0.window == nil }))
    

    You'll get [true, true], proving that the text fields are not yet in any window. But first responder status is window-based; a free-floating text field cannot be first responder.