How do I validate TextFields in an UIAlertController?

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

    For Swift 4.2 (NSNotification.Name.UITextFieldTextDidChange) update:

    let alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        let saveAction = UIAlertAction(title:"Save", style: .destructive, handler: { (action) -> Void in
    
        })
        alert.addAction(saveAction)
        alert.addTextField(configurationHandler: { (textField) in
            textField.placeholder = "Enter something"
            NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main) { (notification) in
                saveAction.isEnabled = textField.text?.count > 0
            }
        })
        present(alert, animated: true, completion: nil)
    

提交回复
热议问题