如何根据 UIAlertController 中的 UITextField 禁用 UIAlertAction?

How to disable UIAlertAction depending on UITextField in UIAlertController?

我正在使用 UIAlertController 向用户显示一个对话框以输入 5 位 CRN。我希望 Add 按钮被禁用,直到 UITextField 中有 5 个且只有 5 个数字。

这是 UI 的样子:

这是 UIAlertController 的属性设置:

var alertController: UIAlertController!

var addAlertAction: UIAlertAction! {
    return UIAlertAction(title: "Add", style: .default)
}

下面是我在 viewDidLoad 方法中初始化它们的方式:

self.alertController = UIAlertController(title: "Add Class", message: "Input CRN", preferredStyle: .alert)
self.alertController.addAction(addAlertAction)
self.alertController.addAction(UIAlertAction(title: "Cancel", style: .destructive))
self.alertController.addTextField { (textField) in
    textField.delegate = self
    textField.keyboardType = .numberPad
}

以下是我尝试使用 UITextFieldDelegate 方法 disable/enable 按钮的方法:

func textFieldDidEndEditing(_ textField: UITextField) {
    if ((textField.text?.characters.count)! == 5) {
        self.alertController.actions[0].isEnabled = true
    } else {
        self.alertController.actions[0].isEnabled = false
    }
}

但是,该按钮始终保持禁用(或启用)状态。它永远不会被启用。出了什么问题?

尝试使用文本字段的 EditingChanged 事件如下:

let addAction:UIAlertAction = UIAlertAction(title: "Add", style: .default)
addAction.isEnabled = false; //to make it disable while presenting

self.alertController = UIAlertController(title: "Add Class", message: "Input CRN", preferredStyle: .alert)
self.alertController.addAction(addAction)
self.alertController.addAction(UIAlertAction(title: "Cancel", style: .destructive))
self.alertController.addTextField { (textField) in
    textField.keyboardType = .numberPad
    textField.addTarget(self, action: #selector(self.alertTextFieldDidChange(field:)), for: UIControlEvents.editingChanged)
}

文本字段的侦听器应如下所示:

func alertTextFieldDidChange(field: UITextField){
    let alertController:UIAlertController = self.presentedViewController as! UIAlertController;
    let textField :UITextField  = alertController.textFields![0];
    let addAction: UIAlertAction = alertController.actions[0];
    addAction.isEnabled = (textField.text?.characters.count)! >= 5;

}

使用 Xcode 8 和 swift 3 测试。对我有用。

实现 UITextFieldshouldChangeCharactersIn 委托方法中的逻辑。此方法在文本字段的每个字符发生变化时被触发。 您可以构建考虑范围参数的逻辑。

这是完美运行的代码。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if ((range.location == 4 && range.length == 0) || (range.location == 5 && range.length == 1)) {
        self.alertController.actions[0].isEnabled = true
    }else{
        self.alertController.actions[0].isEnabled = false
    }

    return true;
}

Swift 3XCode 8iOS 10

中测试成功

希望对您有所帮助。 快乐编码...