限制复制和字符限制在swift中粘贴UITextView?

时间:2017-07-06 17:26:36

标签: 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)
}

1 个答案:

答案 0 :(得分:0)

你可以试试这个,虽然它会因“撤消”而崩溃:

func textViewDidChange(_ textView: UITextView) {
    textView.text = String(textView.text.prefix(200))
}

这将防止错误,但它并不理想,因为如果超过限制,用户将失去撤消的能力:

func textViewDidChange(_ textView: UITextView) {
    if textView.text.count > 200 { textView.undoManager?.removeAllActions() }
    textView.text = String(textView.text.prefix(200))
}
相关问题