Enable UIAlertAction of UIAlertController only after input

前端 未结 6 1699
感情败类
感情败类 2020-12-16 01:39

I am using a UIAlertController to present a dialog with a UITextField and one UIAlertAction button labeled \"Ok\". How do I disable th

6条回答
  •  星月不相逢
    2020-12-16 01:49

    Swift 3 implementation based on soulshined's answer:

    var someAlert: UIAlertController {
        let alert = UIAlertController(title: "Some Alert", message: nil, preferredStyle: .alert)
    
        alert.addTextField {
            $0.placeholder = "Write something"
            $0.addTarget(self, action: #selector(self.textFieldTextDidChange(_:)), for: .editingChanged)
        }
    
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
    
        let submitAction = UIAlertAction(title: "Submit", style: .default) { _ in
            // Do something...
        }
    
        submitAction.isEnabled = false
        alert.addAction(submitAction)
        return alert
    }
    
    func textFieldTextDidChange(_ textField: UITextField) {
        if let alert = presentedViewController as? UIAlertController,
            let action = alert.actions.last,
            let text = textField.text {
            action.isEnabled = text.characters.count > 0
        }
    }
    

提交回复
热议问题