Alert action disabling depending on textField input

I want to know how to disable an alert action if there is no text in the alert text field and enable it as soon as the user enters a character in the text field.


We all have seen in the "Photos" app while adding a new album an alert pops-up, and the Add button is disabled.

But when the user types something, the Add button gets enabled, and if the user removes the text the button get disabled.


Please tell me how to do.

And thank you in advance.

Could do like this : (inspired from h ttps://useyourloaf.com/blog/uialertcontroller-changes-in-ios-8/)


In the textField handler, create a target action (alertTextFieldDidChange) to test if the field is empty.

This action will enable the yesButton if textField (here there is a unique tectField) is not empty

Declare alert in the viewController


    var alert : UIAlertController?

    @objc func alertTextFieldDidChange(_ sender: UITextField) {
        alert?.actions[0].isEnabled = sender.text!.count > 0
    }

    @IBAction func testAlert(_ sender: Any) {

        //1. Create the alert controller.
        alert = UIAlertController(title: "Search", message: "Test empty name ", preferredStyle: .alert)

        //2. Add the text field. If empty, the target action will disable yesAction
        alert?.addTextField(configurationHandler: { (textField) -> Void in
            textField.placeholder = ""
            textField.keyboardType = UIKeyboardType.emailAddress // Just to select one
            textField.addTarget(self, action: #selector(self.alertTextFieldDidChange(_:)), for: .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]
          // Do anything you need here
        })
        yesAction.isEnabled = false          // Initially disabled
        alert?.addAction(yesAction)

        // 4. Present the alert.
        self.present(alert!, animated: true, completion: nil)

    }
Alert action disabling depending on textField input
 
 
Q