Hi all,
I'm struggling to find a way to disable buttons in a UIAlertController of .alert style. I have a textfield, for entering the current password, a button for changing the current password and a button for deleting it. I'd like to disable both password buttons until the current password is correctly entered into the textfield, but I'm struggling to find the solution. If anyone can point me in the right direction it would be much appreciated.
Here is a template for this (example: ask for a city name ; Search button enabled if name non empty).
Alert is called when tapping a button: here is the IBAction:
var alert : UIAlertController? // Declared in the class
@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 // To have @ ; or any other keyboard type you wish
textField.addTarget(self, action: #selector(self.alertTextFieldDidChange(_:)), for: UIControl.Event.editingChanged) // Action when we type in textField
})
//3. Grab the value from the text field. At the end, when hitting search
let yesAction = UIAlertAction(title: "Search", style: .default, handler: { (action) -> Void in
let textField = self.alert?.textFields![0]
if textField?.text! == "" { // When we have hit Search, if enabled
print("empty")
} else {
print("not empty", textField?.text! ?? "")
}
})
yesAction.isEnabled = false
alert?.addAction(yesAction) // Disabled on alert creation
// 4. Present the alert.
self.present(alert!, animated: true, completion: nil)
}
// Test if textField empty ; note that it was created disabled
@objc func alertTextFieldDidChange(_ sender: UITextField) {
alert?.actions[0].isEnabled = sender.text!.count > 0
}
Hope that helps.