Check on UIAlertController TextField for enabling the button

后端 未结 4 960
北恋
北恋 2020-12-13 09:49

I have an AlertController with a text field and two button: CANCEL and SAVE. This is the code:

@IBAction func addTherapy(sender: AnyObject)
{
    let addAler         


        
4条回答
  •  -上瘾入骨i
    2020-12-13 10:01

    There is a much simpler way without using notification center, in swift:

    weak var actionToEnable : UIAlertAction?
    
    func showAlert()
    {
        let titleStr = "title"
        let messageStr = "message"
    
        let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.alert)
    
        let placeholderStr =  "placeholder"
    
        alert.addTextField(configurationHandler: {(textField: UITextField) in
            textField.placeholder = placeholderStr
            textField.addTarget(self, action: #selector(self.textChanged(_:)), for: .editingChanged)
        })
    
        let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: { (_) -> Void in
    
        })
    
        let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (_) -> Void in
            let textfield = alert.textFields!.first!
    
            //Do what you want with the textfield!
        })
    
        alert.addAction(cancel)
        alert.addAction(action)
    
        self.actionToEnable = action
        action.isEnabled = false
        self.present(alert, animated: true, completion: nil)
    }
    
    func textChanged(_ sender:UITextField) {
        self.actionToEnable?.isEnabled  = (sender.text! == "Validation")
    }
    

提交回复
热议问题