文本框计数在迅速4中使用键盘删除字符后显示前一个字符

问题描述 投票:0回答:1

我已经使用了文本框。我需要计算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; }
请帮助我查找当前文本
swift4.2
1个回答
2
投票
您使用错误的代码来确定更新后的文本。请记住,可以删除,替换或添加任意数量的文本,并且根据当前选择,文本可以在字符串的任何位置发生。

您的代码应如下所示:

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 }

此代码中的强制展开是安全的。 textUITextField属性永远不会返回nil,并且除非Apple在UIKit中引入了错误,否则范围转换将始终成功。

也请注意,characters的使用已被弃用了一段时间。 Swift不需要在行尾使用分号,也不需要在if语句中加括号。

© www.soinside.com 2019 - 2024. All rights reserved.