我限制用户在输入或复制粘贴文本时不得超过 200 个字符。假设我的文本字符数为 190。现在我只能再输入 10 个字符。即使我粘贴 200 个字符,它也只会粘贴复制文本的前 10 个字符。
现在的问题是当用户从 UITextView 中选择几个词时。这里单词仍然被选中为突出显示。现在,当我将复制的单词粘贴到选定的单词上时,即使限制为 200,它也允许粘贴更多字符。
代码:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) {
let str = (textView.text! as NSString).replacingCharacters(in: range, with: text)
if str.length >= 200 {
let index = str.index(str.startIndex, offsetBy: 200)
textView.text = str.substring(to: index).trim
}
let remainChars = 200 - textView.text!.length
self.descriptionCountLabel.text? = String(remainChars)
}
最佳答案
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if range.length >= 200 && text.isEmpty {
return false
}
let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
if newText.count > 200 {
textView.text = String(newText.prefix(200))
}
return newText.count <= 200
}
它将防止撤消崩溃,但如果粘贴的文本大于您的限制也不会撤消。
关于ios - 快速限制在 UITextView 中复制和粘贴的字符限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44955447/