How do I validate TextFields in an UIAlertController?

后端 未结 10 2279
不思量自难忘°
不思量自难忘° 2020-12-14 08:54

Can anyone tell me how to validate UITextFields inside of a UIAlertController?

I need it to prevent the user from clicking \"Save\" unless

10条回答
  •  感情败类
    2020-12-14 09:00

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

    //...
    alert.addTextFieldWithConfigurationHandler {
        (textFieldEmail: UITextField!) in
        textFieldEmail.placeholder = "Enter valid email adress"
        textFieldEmail.keyboardType = .EmailAddress
    }   
    
    let textFieldValidationObserver: (NSNotification!) -> Void = { _ in
        let textFieldName = alert.textFields![0] as! UITextField
        let textFieldEmail = alert.textFields![1] as! UITextField
        saveAction.enabled = self.isValidEmail(textFieldEmail.text) && textFieldName.text.length > 0
    }
    
    // Notifications for textFieldName changes
    NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification,
        object: alert.textFields![0],  // textFieldName
        queue: NSOperationQueue.mainQueue(), usingBlock: textFieldValidationObserver)
    
    // Notifications for textFieldEmail changes
    NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification,
        object: alert.textFields![1],  // textFieldEmail
        queue: NSOperationQueue.mainQueue(), usingBlock: textFieldValidationObserver)
    
    alert.addAction(saveAction)
    //...
    

提交回复
热议问题