Vpor
Vpor

Reputation: 157

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

Upvotes: 0

Views: 2445

Answers (3)

Rajat
Rajat

Reputation: 11127

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
}        
alert.addAction(alertAction)
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

Upvotes: 6

Surjeet Rajput
Surjeet Rajput

Reputation: 1301

You can TextFieldDelegate. Set your current view Controller or view as a delegate.like

let textTextField = UITextField()
textTextField.delegate = self

when textfield change the below method will be called.

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

or you can use the notification UITextFieldTextDidChange .it will posted when text of textfield will change.

The affected text field is stored in the object parameter of the notification.

Upvotes: 0

Marie Dm
Marie Dm

Reputation: 2727

Check text field text:

if textField.text != nil && textField.text != "" {
    print("you can enable your add button")
}else{
    print("empty text field")
}

Upvotes: -1

Related Questions