首页 > 解决方案 > 在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;
 }

请帮我找到当前文本

标签: swift4.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
}

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

另请注意,使用 ofcharacters已被弃用一段时间。而且 Swift 不需要在行尾使用分号,也不需要在if语句中使用括号。


推荐阅读