jo1995
jo1995

Reputation: 414

How to enable/disable Alert action?

I want to enable the action of the alert only if the user has type in some input with the following codelines:

var alert: UIAlertController!

func alertBeitrageMelden(postId: String){

    self.alert = UIAlertController(title: "Beitrag melden", message: "Wieso möchtest du den Beitrag melden?", preferredStyle: .alert)

    let defaultAction = UIAlertAction(title: "Melden", style: .default) { (action) in

        if let text = self.alert.textFields?.first?.text, text.count > 0 {
            let postTime = Date().timeIntervalSince1970
            let ref = Database.database().reference().child("gemeldeteBeitraege").child(postId)
            ref.setValue(["postId": postId, "reason": text, "time": postTime])
            ProgressHUD.showSuccess("Der Beitrag wurde gemeldet", interaction: false)
        }
    }

    let cancelAction = UIAlertAction(title: "Abbrechen", style: .cancel) { (action) in
    }

    alert.addTextField { (textField) in
        textField.placeholder = ""
        textField.delegate = self
    }

    alert.addAction(defaultAction)
    alert.addAction(cancelAction)



    self.present(alert, animated: true) {
    }
}

Here I check if the user typed in something:

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

    if (textField.text?.count)! > 0 {
        self.alert.actions[0].isEnabled = true
    }else{
        self.alert.actions[0].isEnabled = false
    }

    return true;
}

But its still not working.

Thanks in advance for your help!

Upvotes: 1

Views: 690

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Do this

textField.addTarget(self, action: #selector(self.textEdited), for: .editingChanged)

@objc func textEdited(_ textField:UITextField) {

    if textField.text!.count > 0 {
        alert.actions.first?.isEnabled = true
    }else{
        alert.actions.first?.isEnabled = false
    }

}

Add this line that will disable it initially

 alert.actions.first?.isEnabled = false
 self.present(alert, animated: true)

Upvotes: 2

Related Questions