我已经使用了文本框。我需要计算11个字符后才能调用函数的字符。功能正常工作。但是当我删除一个字符时,它会显示前一个字符。我在文本字段中输入了[[01921687433。但是,当从该数字中删除一个字符时,例如0192168743,它将显示全数字11位数字,而不显示10位数字。但文本字段显示0192168743。这是我的代码。.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//print("While entering the characters this method gets called")
let currentText = textField.text! + string
if(currentText.characters.count == 11){
print("account 11 digit =", currentText)
//Action here
}
return true;
}
请帮助我查找当前文本
您的代码应如下所示:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newText = textField.text!.replacingCharacters(in: Range(range, in: textField.text!)!, with: string)
if newText.count == 11 {
print("account 11 digit = \(newText)")
}
return true
}
此代码中的强制展开是安全的。text
的UITextField
属性永远不会返回nil
,并且除非Apple在UIKit中引入了错误,否则范围转换将始终成功。也请注意,
characters
的使用已被弃用了一段时间。 Swift不需要在行尾使用分号,也不需要在if
语句中加括号。