[英]Check live if UITextField is not empty
我有一個包含UITextField的UIAlertView。 警報視圖具有兩個按鈕。 一個普通的“關閉”按鈕,另一個“添加”按鈕。 如果UITextField不為空,則只需單擊“添加”按鈕。 如果字段為空,我不知道如何“實時”簽入。 我只看到檢查按鈕是否被單擊的textField的可能性。 但這不是想要的(如果thextField為空,則“添加”按鈕應顯示為灰色)。 您對此有解決方案嗎? 謝謝你的努力!
我正在使用Swift 3和Xcode 8
您需要像這樣將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
}
這是一個有效的例子
檢查文字欄位文字:
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。當文本字段的文本更改時,它將發布。
受影響的文本字段存儲在通知的object參數中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.