Vpor Vpor - 1 year ago 125
Swift Question

Check live if UITextField is not empty

I have a UIAlertView which includes an UITextField. The alert view has tow buttons. One normal "dismiss" button and another "add". The "add" button should just be clickable if the UITextField is not empty. I don't know how to check in "real time" if the field is empty. I only saw the possibility to check the textField if the button has been clicked. But that's not what want ("add" button should be grayed out if thextField is empty). Do you have a solution for this? Thanks for your effort!

I'm using Swift 3 and Xcode 8

Answer Source

You need to create you UIAlertAction as a global variable like this

var alertAction = UIAlertAction()

Now while adding that action to UIAlertController you need to set the property isEnabled as false like in the below code

alertAction = UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil)
alertAction.isEnabled = false
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addTextField { (textField) in
    textField.delegate = self
self.present(alert, animated: true, completion: nil)

After this in the delegate method shouldChangeCharacter you need to get if the value is entered in the UITextField then you need to enable that button like this

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let userEnteredString = textField.text
        let newString = (userEnteredString! as NSString).replacingCharacters(in: range, with: string) as NSString
        if  newString != ""{
            alertAction.isEnabled = true
        } else {
            alertAction.isEnabled = false
        return true

Here is a working example

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download