如果 UITextField 不为空,请实时检查 [英] Check live if UITextField is not empty
问题描述
我有一个 UIAlertView,其中包含一个 UITextField.警报视图有两个按钮.一个正常的关闭"按钮和另一个添加"按钮.如果 UITextField 不为空,添加"按钮应该是可点击的.如果该字段为空,我不知道如何实时"检查.如果单击了按钮,我只看到了检查 textField 的可能性.但这不是想要的(如果 xtField 为空,添加"按钮应该变灰).你有解决办法吗?感谢您的努力!
I have a UIAlertView which includes an UITextField. The alert view has tow buttons. One normal "dismiss" button and another "add". The "add" button should just be clickable if the UITextField is not empty. I don't know how to check in "real time" if the field is empty. I only saw the possibility to check the textField if the button has been clicked. But that's not what want ("add" button should be grayed out if thextField is empty). Do you have a solution for this? Thanks for your effort!
我使用的是 Swift 3 和 Xcode 8
I'm using Swift 3 and Xcode 8
推荐答案
你需要像这样创建 UIAlertAction 作为全局变量
You need to create you UIAlertAction as a global variable like this
var alertAction = UIAlertAction()
现在,在将该操作添加到 UIAlertController 时,您需要将属性 isEnabled
设置为 false,如下面的代码所示
Now while adding that action to UIAlertController you need to set the property isEnabled
as false like in the below code
alertAction = UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil)
alertAction.isEnabled = false
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addTextField { (textField) in
textField.delegate = self
}
alert.addAction(alertAction)
self.present(alert, animated: true, completion: nil)
在委托方法 shouldChangeCharacter 之后,您需要获取是否在 UITextField 中输入了该值,然后您需要像这样启用该按钮
After this in the delegate method shouldChangeCharacter you need to get if the value is entered in the UITextField then you need to enable that button like this
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let userEnteredString = textField.text
let newString = (userEnteredString! as NSString).replacingCharacters(in: range, with: string) as NSString
if newString != ""{
alertAction.isEnabled = true
} else {
alertAction.isEnabled = false
}
return true
}
这是一个工作示例
这篇关于如果 UITextField 不为空,请实时检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!