Sam*_*her 5 uitextfield ios uialertcontroller swift3 ios10
我正在使用a UIAlertController
向用户显示一个对话框,输入一个5位数的CRN.我希望Add
按钮被禁用,直到有5个且只有5个数字UITextField
.
这是UI的样子:
这是以下属性设置UIAlertController
:
var alertController: UIAlertController!
var addAlertAction: UIAlertAction! {
return UIAlertAction(title: "Add", style: .default)
}
Run Code Online (Sandbox Code Playgroud)
以下是我在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
}
Run Code Online (Sandbox Code Playgroud)
以下是我尝试使用以下UITextFieldDelegate
方法禁用/启用按钮的方法:
func textFieldDidEndEditing(_ textField: UITextField) {
if ((textField.text?.characters.count)! == 5) {
self.alertController.actions[0].isEnabled = true
} else {
self.alertController.actions[0].isEnabled = false
}
}
Run Code Online (Sandbox Code Playgroud)
但是,该按钮始终处于禁用(或启用)状态.它永远不会启用.出了什么问题?
Adi*_*mro 10
尝试使用文本字段的 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)
}
Run Code Online (Sandbox Code Playgroud)
文本字段的侦听器应如下所示:
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;
}
Run Code Online (Sandbox Code Playgroud)
使用 Xcode 8 和 swift 3 进行测试。为我工作。
在shouldChangeCharactersIn
委托方法中实现逻辑UITextField
.此方法在文本字段的每个字符的更改时被触发.您可以构建考虑范围参数的逻辑.
这是完美运行的代码.
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;
}
Run Code Online (Sandbox Code Playgroud)
测试成功Swift 3
,XCode 8
和iOS 10
希望有所帮助.快乐的编码......
归档时间: |
|
查看次数: |
3735 次 |
最近记录: |