I have a UIAlertController
(Alert style) in Swift and it all works just fine. However, the UITextField
that I have added to it is an optional field that the user is not required to enter text into. The problem is when I show this UIAlertController
, the keyboard appears simultaneously with the text field selected by default. I don't want the keyboard to appear unless the user taps the UITextField
. How can this be done?
let popup = UIAlertController(title: "My title",
message: "My message",
preferredStyle: .Alert)
popup.addTextFieldWithConfigurationHandler { (optionalTextField) -> Void in
optionalTextField.placeholder = "This is optional"
}
let submitAction = UIAlertAction(title: "Submit", style: .Cancel) { (action) -> Void in
let optionalTextField = popup.textFields![0]
let text = optionalTextField.text
print(text)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
popup.addAction(cancelAction)
popup.addAction(submitAction)
self.presentViewController(popup, animated: true, completion: nil)
this should do the trick:
make your viewController conform to UITextFieldDelegate
assign the popup.textFields![0].delegate
to self
add unique tag to popup.textFields![0]
(i used 999 in the example below)
implement this
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if textField.tag == 999 {
textField.tag = 0
return false
}else{
return true
}
}
your code should look like this:
let popup = UIAlertController(title: "My title",
message: "My message",
preferredStyle: .Alert)
popup.addTextFieldWithConfigurationHandler { (optionalTextField) -> Void in
optionalTextField.placeholder = "This is optional"
}
popup.textFields![0].delegate = self
popup.textFields![0].tag = 999
let submitAction = UIAlertAction(title: "Submit", style: .Cancel) { (action) -> Void in
let optionalTextField = popup.textFields![0]
let text = optionalTextField.text
print(text)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
popup.addAction(cancelAction)
popup.addAction(submitAction)
self.presentViewController(popup, animated: true, completion: nil)
I think this is the default behaviour for a textField in an alert, maybe consider an alternative design so that the textfield only shows up when it is necessary...
Now with that out of the way let's circumvent this!
When you add the textField make your viewController it's delegate and add a tag to it.
eg
popup.addTextFieldWithConfigurationHandler { (optionalTextField) -> Void in
optionalTextField.placeholder = "This is optional"
optionalTextField.delegate = self
optionalTextField.tag = -1
}
then implement textFieldShouldBeginEditing()
func textFieldShouldBeginEditing(textField: UITextField!) {
if textField.tag == -1 {
textField.tag = 0
return false
} else {
return true
}
}
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