限制字符后,iOS Backspace在UIextView中不起作用

nnsrf1az  于 2023-06-25  发布在  iOS
关注(0)|答案(1)|浏览(104)

我想限制允许用户在UITextView中输入的字符数。为此,我使用委托方法shouldChangeTextInRange。
我现在遇到的问题是如何检测退格键逃逸。工作很好,但退格不。
如何检测退格键?
有什么想法吗?
这是我的代码

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    {
        if textField == biofield
        {
            if biofield.text == ""
            {
                self.countLbl.text = "0/40"
            }
            else
            {
                let count = self.biofield.text!.count + string.count
                print("Count is ", count)
                self.countLbl.text = "\(count)/40"
            }
            let maxLength = 40          // Set your need
            let currentString: NSString = biofield.text! as NSString
            let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
            return newString.length <= maxLength
            //return false
        }
        else
        {
            return true
        }
    }

非常感谢!

but5z9lq

but5z9lq1#

我曾经遇到过这个问题。这个代码对我很有效

let maxCharacters = 10
// Check if the user is attempting to delete a character
if text.count == 0 && textView.text.count > 0 {
    // Allow the backspace key to delete characters
    return true
}

// Check if the new text will exceed the maximum number of characters
let textCurrent = textView.text as NSString
let textNew = textCurrent.replacingCharacters(in: range, with: text)
return textNew.count <= maxCharacters

请在shouldChangeTextIn函数中检查此代码并告诉我。

相关问题