ios - 快速限制在 UITextView 中复制和粘贴的字符限制?

标签 ios swift uitextview

我限制用户在输入或复制粘贴文本时不得超过 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/

相关文章:

ios - UITextView 和神秘的缺失空间

iOS 8 boundingRectWithSize 计算错误的文本大小

ios - Swift 逆向保护问题

ios - 在静态表格 View 中动态调整 TextView 和表格 View 单元格的大小

ios - 圆角 : How to calculate Fillet radius?

objective-c - 没有 UIControls 响应用户事件

swift - Filter Realm Results 数组返回应过滤的元素

ios - DocuSign 复写本未收到通知

ios - 为什么 iOS 在 didReceiveMemoryWarning 释放后不自动旋转从 Nib 加载的 View ?

objective-c - 了解第一响应者的系统逻辑