【问题标题】:Allow user to delete textfield text but restrict maximum text length [duplicate]允许用户删除文本字段文本但限制最大文本长度[重复]
【发布时间】:2019-10-17 00:22:22
【问题描述】:

我有UITextField,我希望用户最多只能输入 4 个符号。但我也想让他们用键盘擦除符号(我的意思是,删除最后一个并将插入符号向左移动。符号看起来像 iOS 键盘上带有十字的矩形左箭头)。

现在我结束了:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text, text.count < 4 else { return false }
    return true
  }

但我不知道如何让用户删除符号。当文本计数变为 4 时,我将无法输入或执行任何操作。

【问题讨论】:

    标签: ios swift uitextfield


    【解决方案1】:

    您必须在“应更改字符范围”方法中检查长度。喜欢关注

     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
        let newLength = textField.text.length + (string.length - range.length)
    
        if newLength <= maxLength {
           return true
        } else {
           return false 
        }
    }
    

    这里的 maxLength 是您希望允许的最大字符长度

    【讨论】:

    • 您的代码无法编译。
    【解决方案2】:

    使用这个

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return textField.text!.count + string.count < 5
    }
    

    【讨论】:

    • 我会感谢我对我的回答投反对票的原因!!!
    • 使用您的代码,即使文本长度超过 4,用户也可以在小于 4 的位置插入一些字符。
    • 谢谢@OOPer,你是对的。
    • 很好的答案,比我在链接线程中找到的要好。
    【解决方案3】:

    您可以使用下面的代码来获取更新的字符串并将其与您的长度进行比较,

    func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
      // limit to 4 characters
      let characterCountLimit = 4
    
      // We need to figure out how many characters would be in the string after the change happens
      let startingLength = textFieldToChange.text?.count ?? 0
      let lengthToAdd = string.count
      let lengthToReplace = range.length
    
      let newLength = startingLength + lengthToAdd - lengthToReplace
    
      return newLength <= characterCountLimit
    }
    

    【讨论】:

    • 当范围不为空时,您的currentText 可能是错误的。
    • 如果出现任何问题,请尝试此操作,然后告诉我
    • 填4个字符,全选,然后输入1个字符。
    • 试试这个更新的代码
    • 已改进,但等同于链接中已批准答案的 Swift 代码。
    【解决方案4】:

    来自textField(_:shouldChangeCharactersIn:replacementString:)的文档

    当用户删除一个或多个字符时,替换字符串为空。

    因此,您所缺少的只是检查替换字符串是否为空:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return string.isEmpty || (textField.text?.count ?? 0) < 4
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 1970-01-01
      • 2014-04-30
      • 2013-02-16
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      相关资源
      最近更新 更多