How do I validate TextFields in an UIAlertController?

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

    Most elegant way is to use

    NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextFieldTextDidChange...
    

    Swift 3.0 example

    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: NSNotification.Name.UITextFieldTextDidChange, object: textField, queue: OperationQueue.main) { (notification) in
                saveAction.isEnabled = textField.text!.length > 0
            }
        })
        present(alert, animated: true, completion: nil)
    

提交回复
热议问题