I have an UIAlertController with a textfield in it, like this:
let alertController = UIAlertController(title: "Title", message: "Hello, World!", preferredStyle: .Alert)
let someAction = UIAlertAction(title: "Action", style: .Default) { (_) in }
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) {(_) in }
alertController.addAction(someAction)
alertController.addAction(cancelAction)
alertController.addTextFieldWithConfigurationHandler { textfield in
textfield.text = "Text"
}
self.presentViewController(alertController, animated: true, completion: nil)
When the controller is presented, the textfield has focus and the keyboard comes up. Is it possible to change that behavior so that the textfield only becomes first responder when the user taps on it? I don't want the keyboard to be presented at the same time the alert controller is presented.
Here's one slightly hacky solution that involves associated objects and method swizzling.
The idea is to give
UITextField
a closure that gives outside classes a say in whether a text field can become the first responder or not. This closure passes back boolean value indicating whether the text field is trying to become the first responder due to user interaction or due tocanBecomeFirstResponder
having been programmatically called on the text field. It also passes back the value thatcanBecomeFirstResponder
would return normally in thedefaultValue
parameter -- this isn't needed in this case, but as a general solution it could be useful to have.First, we add the
UITextField
extension that will handle the swizzling and associated object stuff:Then, you can use this closure in your alert controller text field configuration handler like so:
Old solution that no longer works:
Adding this:
right before presenting the alert controller will resign first responder from all text fields and prevent the keyboard from appearing while presenting.