我想限制允许用户在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
}
}
非常感谢!
1条答案
按热度按时间but5z9lq1#
我曾经遇到过这个问题。这个代码对我很有效
请在shouldChangeTextIn函数中检查此代码并告诉我。