如果 UITextField 不为空,请实时检查

Vpo*_*por 0 uitextfield uialertview ios swift xcode8

我有一个 UIAlertView,其中包括一个 UITextField。警报视图有两个按钮。一个正常的“关闭”按钮和另一个“添加”按钮。如果 UITextField 不为空,“添加”按钮应该是可点击的。如果该字段为空,我不知道如何“实时”检查。如果单击了按钮,我只看到了检查 textField 的可能性。但这不是想要的(如果 xtField 为空,“添加”按钮应该变灰)。你有解决办法吗?谢谢你的努力!

我正在使用 Swift 3 和 Xcode 8

Raj*_*jat 5

您需要像这样创建 UIAlertAction 作为全局变量

var alertAction = UIAlertAction()
Run Code Online (Sandbox Code Playgroud)

现在,在将该操作添加到 UIAlertController 时,您需要isEnabled像下面的代码一样将该属性设置为 false

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)
Run Code Online (Sandbox Code Playgroud)

在此之后,在委托方法 shouldChangeCharacter 中,您需要获取是否在 UITextField 中输入了该值,然后您需要像这样启用该按钮

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
    }
Run Code Online (Sandbox Code Playgroud)

这是一个工作示例

在此处输入图片说明