检查 UITextField 是否为空

Check live if UITextField is not empty

我有一个包含 UITextField 的 UIAlertView。警报视图有两个按钮。一个普通 "dismiss" 按钮和另一个 "add"。如果 UITextField 不为空,则 "add" 按钮应该是可点击的。如果该字段为空,我不知道如何签入 "real time"。如果单击了按钮,我只看到了检查 textField 的可能性。但这不是我们想要的(如果 thextField 为空,"add" 按钮应该变灰)。你有解决办法吗?感谢您的努力!

我正在使用 Swift 3 和 Xcode 8

检查文本字段文本:

if textField.text != nil && textField.text != "" {
    print("you can enable your add button")
}else{
    print("empty text field")
}

您可以使用 TextFieldDelegate。将您当前的视图控制器或视图设置为 delegate.like

let textTextField = UITextField()
textTextField.delegate = self

当文本字段发生变化时,将调用以下方法。

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

或者您可以使用通知 UITextFieldTextDidChange。它会在文本字段的文本更改时发布。

受影响的文本字段存储在通知的对象参数中。

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

var alertAction = UIAlertAction()

现在,在将该操作添加到 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)

在委托方法 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
    }

这是一个工作示例