I'm using a UIAlertController
to present the user with a dialog to enter a 5 digit CRN. I want the Add
button to be disabled until there are 5 and only 5 digit in the UITextField
.
Here's what the UI looks like :
Here's the properties setup for the UIAlertController
:
var alertController: UIAlertController!
var addAlertAction: UIAlertAction! {
return UIAlertAction(title: "Add", style: .default)
}
Here's how I'm initializing them in the viewDidLoad
method :
self.alertController = UIAlertController(title: "Add Class", message: "Input CRN", preferredStyle: .alert)
self.alertController.addAction(addAlertAction)
self.alertController.addAction(UIAlertAction(title: "Cancel", style: .destructive))
self.alertController.addTextField { (textField) in
textField.delegate = self
textField.keyboardType = .numberPad
}
Here's how I'm trying to disable/enable the button using the UITextFieldDelegate
method :
func textFieldDidEndEditing(_ textField: UITextField) {
if ((textField.text?.characters.count)! == 5) {
self.alertController.actions[0].isEnabled = true
} else {
self.alertController.actions[0].isEnabled = false
}
}
However, the button remains disabled (or enabled) all the time. It never gets enabled. What's going wrong ?
Try using the textfield's EditingChanged event as follow:
And the listener for text field should look like this:
Tested with Xcode 8 and swift 3. Worked for me.
Implement the logic in the
shouldChangeCharactersIn
delegate method ofUITextField
. This method gets fired on change in each character of textfield. You can build the logic taking the range parameter into consideration.Here is the code that works perfectly.
Tested successfully in
Swift 3
,XCode 8
andiOS 10
Hope that helps. Happy coding ...