如何根据UIAlertController中的UITextField禁用UIAlertAction? [英] How to disable UIAlertAction depending on UITextField in UIAlertController?

查看:95
本文介绍了如何根据UIAlertController中的UITextField禁用UIAlertAction?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using a UIAlertController to present the user with a dialog to enter a 5 digit CRN. I want the Add button to be disabled until there are 5 and only 5 digit in the UITextField.

UI如下所示:

这是 UIAlertController 的属性设置:

var alertController: UIAlertController!

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

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

Here's how I'm initializing them in the viewDidLoad method :

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 方法禁用/启用按钮的方式:

Here's how I'm trying to disable/enable the button using the UITextFieldDelegate method :

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

但是,按钮始终保持禁用(或启用)状态.它永远不会启用.怎么了?

However, the button remains disabled (or enabled) all the time. It never gets enabled. What's going wrong ?

推荐答案

UITextField shouldChangeCharactersIn 委托方法中实现逻辑.当文本字段的每个字符发生更改时,都会触发此方法.您可以考虑范围参数来构建逻辑.

Implement the logic in the shouldChangeCharactersIn delegate method of UITextField. This method gets fired on change in each character of textfield. You can build the logic taking the range parameter into consideration.

这是完美运行的代码.

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 3 XCode 8 iOS 10

希望有帮助.编码愉快...

Hope that helps. Happy coding ...

这篇关于如何根据UIAlertController中的UITextField禁用UIAlertAction?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆