swift4.2 - 在swift 4中使用键盘删除字符后,文本字段计数显示前一个字符
问题描述
我用过文本字段。我需要计算字符以在 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 中引入错误。
另请注意,使用 ofcharacters
已被弃用一段时间。而且 Swift 不需要在行尾使用分号,也不需要在if
语句中使用括号。
推荐阅读
- macos - Flutter - 如何在 MacOS 应用程序中使用 smb 映射网络驱动器?
- angular - 如何动态更改(完全替换)GoJS 中的 diagram.model?
- python-3.x - 如何在字符串中查找包含没有任何后缀和前缀的字符串的行?
- artifactory - 禁用修订时,无法将柯南包上传到 Artifactory 服务器
- c - C. double数组和char数组中realloc的区别
- c++ - doopen():“无法从共享对象映射段”当不以root身份运行时
- javascript - createjs off() 函数从 js 箭头函数中删除监听器
- java - Java 8:转换地图
> 到地图 - ios - 如何检测iOS中音量的变化?
- elasticsearch - 如何在 Elasticsearch 中的多个索引之间进行聚合