Disable button in UIAlertView while text field is empty
Asked Answered
L

3

6

I make an AlertViewController with textField that asks user to type a name of new item for data model.

So I want to keep submit button disabled while text field is empty. In other case, when I create @IBOutlet in ViewController for textfield from storyboard I could just use some methods from UITextFieldDelegate protocol and solve problem without your help.

But now I can't.

Lyonnaise answered 13/5, 2016 at 9:44 Comment(2)
Check this link, it may help you: useyourloaf.com/blog/uialertcontroller-changes-in-ios-8Scoop
Thanks, very useful, but it takes time to translate to my native language - swift, but I already see the answer...Lyonnaise
N
12

Register for the text field change notifications and validate the text fields there:

@IBAction func showAlert(sender: AnyObject) {

    var alert = UIAlertController(title: "New user",
        message: "Add a new user",
        preferredStyle: .Alert)

    let saveAction = UIAlertAction(title: "Save",
        style: .Default) { (action: UIAlertAction!) -> Void in

            println("do your stuff here")
    }

    saveAction.enabled = false

    let cancelAction = UIAlertAction(title: "Cancel",
        style: .Default) { (action: UIAlertAction!) -> Void in
    }


    alert.addTextFieldWithConfigurationHandler {
        (textFieldName: UITextField!) in
        textFieldName.placeholder = "Enter full name"
    }

    alert.addTextFieldWithConfigurationHandler {
        (textFieldEmail: UITextField!) in
        textFieldEmail.placeholder = "Enter valid email adress"
        textFieldEmail.keyboardType = .EmailAddress

    }
// adding the notification observer here
 NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification, object:alert.textFields?[0],
        queue: NSOperationQueue.mainQueue()) { (notification) -> Void in

            let textFieldName = alert.textFields?[0] as! UITextField
            let textFieldEmail = alert.textFields![1] as! UITextField
            saveAction.enabled = self.isValidEmail(textFieldEmail.text) &&  !textFieldName.text.isEmpty
    }


    NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification, object:alert.textFields?[1],
        queue: NSOperationQueue.mainQueue()) { (notification) -> Void in

            let textFieldEmail = alert.textFields?[1] as! UITextField
            let textFieldName = alert.textFields?[0] as! UITextField
            saveAction.enabled = self.isValidEmail(textFieldEmail.text) &&  !textFieldName.text.isEmpty
    }


    alert.addAction(saveAction)
    alert.addAction(cancelAction)

    presentViewController(alert,
        animated: true,
        completion: nil)

}

 //  email validation code method
func isValidEmail(testStr:String) -> Bool {
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
    if let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) as NSPredicate? {
        return emailTest.evaluateWithObject(testStr)
    }
    return false
}
Nickolas answered 13/5, 2016 at 9:48 Comment(0)
Q
2

New Swift 4.2 Update

NotificationCenter.default.addObserver(
    forName: UITextField.textDidChangeNotification,
    object: alert.textFields?.first,
    queue: .main
) { notification in
    guard let textFieldText = alert.textFields?.first?.text else { return }
    saveAction.isEnabled = self.isValidEmail(textFieldText) && !textFieldText.isEmpty
}
Quin answered 3/8, 2019 at 15:58 Comment(0)
C
0

add this code in viewDidLoad method

let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(
 self,
 selector: "textFieldTextChanged:",
 name:UITextFieldTextDidChangeNotification,
 object: nil
)

and this method in ViewController

func textFieldTextChanged(sender : AnyObject) {
//your code
}
Citreous answered 13/5, 2016 at 10:6 Comment(1)
Thanks, I thought about using notifications, but had a doubt to use such powerful mechanism for my small task:)Lyonnaise

© 2022 - 2024 — McMap. All rights reserved.