Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable UIAlertAction depending on UITextField in UIAlertController?

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 :

enter image description here

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 ?

like image 785
Sam Fischer Avatar asked Sep 16 '16 18:09

Sam Fischer


1 Answers

Implement the logic in the shouldChangeCharactersIn delegate method of UITextField. 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.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if ((range.location == 4 && range.length == 0) || (range.location == 5 && range.length == 1)) {
        self.alertController.actions[0].isEnabled = true
    }else{
        self.alertController.actions[0].isEnabled = false
    }

    return true;
}

Tested successfully in Swift 3, XCode 8 and iOS 10

Hope that helps. Happy coding ...

like image 182
Janmenjaya Avatar answered Oct 12 '22 17:10

Janmenjaya