简体   繁体   中英

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

I have an array of UITextField s 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM