如果UITextField不为空,请现场检查

我有一个包含UITextField的UIAlertView。 警报视图有两个button。 一个正常的“解雇”button和另一个“添加”。 如果UITextField不为空,“添加”button应该是可点击的。 如果字段是空的,我不知道如何检查“实时”。 我只看到如果button被点击,检查textField的可能性。 但是,这不是什么想(如果theField是空的,“添加”button应该变灰)。 你有这个解决scheme吗? 谢谢你的努力!

我正在使用Swift 3和Xcode 8

你需要像这样创build你的UIAlertAction作为一个全局variables

 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中input了值,那么你需要启用这个button

 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 } 

这是一个工作的例子

在这里输入图像说明

检查文本字段文本:

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

你可以TextFieldDelegate。 设置你当前的视图控制器或视图作为委托

 let textTextField = UITextField() textTextField.delegate = self 

当文本字段更改下面的方法将被调用。

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

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

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