How do I validate TextFields in an UIAlertController?

后端 未结 10 2283
不思量自难忘°
不思量自难忘° 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:05

    First, you need to add some variables to your class:

    private weak var saveAction : UIAlertAction?
    private weak var textFieldName : UITextField?
    private weak var textFieldEmail : UITextField?
    private var validName = false
    private var validEmail = false
    

    Then, when you want to configure the alert controller (I only pasted the things that need to be changed):

        alert.addTextFieldWithConfigurationHandler {
            (textFieldName: UITextField!) in
            textFieldName.placeholder = "Enter full name"
            textFieldName.delegate = self
            self.textFieldName = textFieldName
        }
        alert.addTextFieldWithConfigurationHandler {
            (textFieldEmail: UITextField!) in
            textFieldEmail.placeholder = "Enter valid email adress"
            textFieldEmail.keyboardType = .EmailAddress
            textFieldEmail.delegate = self
            self.textFieldEmail = textFieldEmail
        }
    
        let saveAction = UIAlertAction(title: "Save",
            style: .Default) { (action: UIAlertAction!) -> Void in
            // here you are sure the name and email are correct
            let name = (alert.textFields[0] as! UITextField).text
            let email = (alert.textFields[1] as! UITextField).text
        }
    
        saveAction.enabled = false
        self.saveAction = saveAction
    

    Finally, you should implement this delegate method:

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    
        let newText = NSString(string: textField.text).stringByReplacingCharactersInRange(range, withString: string)
    
        if textField == self.textFieldName {
            // validate newText for the name requirements
            validName = self.validateName(newText)
        } else if textField == self.textFieldEmail {
            // validate newText for the email requirements
            validEmail = self.validateEmail(newText)
        }
    
        self.saveAction?.enabled = validEmail && validName
    
        return true
    }
    

提交回复
热议问题