[英]Swift - how do I make the textfield recognize more than one correct answer in quiz?
[英]How to check if textfield has more than one letter in Swift?
我正在 Swift 中處理一個文本字段,我將要實現的是禁用導航按鈕,除非文本字段中有 0 個字符,如果文本字段中有 1 個以上的字母,則在文本字段上添加刪除按鈕文本字段,如 iOS 默認日歷應用程序。
當標題文本字段中沒有字母時,欄按鈕項“添加”被禁用。
啟用“添加”按鈕並在標題文本字段中有 1+ 個字母時顯示刪除按鈕。
我查看了文本字段委托方法,我想我可以通過使用 shouldChangeCharactersIn 方法(?)
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// check if there is a letter in the text field
// if there is, enable the Add button and show delete icon
// if there is not, disable the add button and hide the delete icon
return true
}
我想知道是否還有其他方法可以實現此功能? 我想每當在文本字段上鍵入/刪除一個字母時,每次都會調用上面的函數,所以我想知道是否有其他方法可以輕松實現這些東西。
func textFieldDidChangeSelection(_ textField: UITextField) {
validateTextField(text:textField.tex)
}
您的方法 shouldChangeCharactersIn 有時無法正常工作,因此可以使用此方法創建一個接收文本並禁用和啟用導航欄和刪除按鈕的功能,例如
func validateTextField(text:String) {
if text.count > 1 {
textField.clearButtonMode = .whileEditing
} else if text.count <= 1 {
textField.clearButtonMode = .never
} else if text.count < 1 {
navigationItem.leftBarButtonItem.tintColor = .lightGray
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.