[英]Limit TextField Input to Capitals letters, Numbers and Character limit of 6?
我在網上進行搜索,發現了很多有關限制TextField的示例,但找不到有關限制多個因素的任何示例。 我正在工作的代碼弄亂了輸入內容,我弄不清原因。
這是我的代碼:(注意:我已經設置了委托)
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = LPinput.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
LPinput.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.uppercased())
return newLength <= limitLength
}
這是我在TextField中鍵入的內容:
餐飲
這是TextField中顯示的內容:
FoOoOD
請幫忙!
就像@rmaddy所說的那樣,問題在於您正在修改UITextField.text
屬性,然后返回true,這會導致在您的問題中出現重復的行為,因此我對此進行了更改,請首先檢查textLength,然后修改文本並返回始終為false,以避免添加重復字符,請嘗試使用此代碼
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = LPinput.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
if(newLength <= limitLength)
{
LPinput.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.uppercased())
}
return false
}
希望這對您有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.