Here is how you create an alert with a TextField.
Declare in the VC
var alert : UIAlertController?
I have embedded in an IBAction to call the alert from a UIButton.
@IBAction func testAlert(_ sender: Any) {
//1. Create the alert controller.
alert = UIAlertController(title: "Search City", message: "City name ", preferredStyle: .alert)
//2. Add the text field.
alert?.addTextField(configurationHandler: { (textField) -> Void in
textField.placeholder = ""
textField.keyboardType = UIKeyboardType.emailAddress // For instance
// alertTextFieldDidChange activate OK button
textField.addTarget(self, action: #selector(self.alertTextFieldDidChange(_:)), for: UIControl.Event.editingChanged)
})
//3. Grab the value from the text field.
let yesAction = UIAlertAction(title: "Search", style: .default, handler: { (action) -> Void in
let textField = self.alert?.textFields![0]
if textField?.text! == "" {
print("empty") // Just for testing, should be removed
} else {
print("not empty", textField?.text! ?? "") // Just for testing, should be removed
}
})
yesAction.isEnabled = false.
alert?.addAction(yesAction) // This will be actions[0]
// 4. Present the alert.
self.present(alert!, animated: true, completion: nil)
}
The handler where we activate OK as soon as a textField not empty
@objc func alertTextFieldDidChange(_ sender: UITextField) {
alert?.actions[0].isEnabled = sender.text!.count > 0
}