Swift UITextView限制输入文本字符数

Swift UITextView限制输入文本字符数

1.实现UITextViewDelegate

func textViewDidChange(_ textView: UITextView) {
        checkShowHiddenPlaceholder()
        // /获取高亮部分
        let selectedRange = textView.markedTextRange
        let pos = textView.position(from: textView.beginningOfDocument, offset: 0)
        
        /// 如果在变化中是高亮部分在变,就不要计算字符了
        if (selectedRange != nil) && (pos != nil) {
            return
        }
        if textView.text.count >= limitWords {
            textView.text = String(textView.text.prefix(limitWords))
        }
        countLabel.text = "\(textView.text.count)/\(limitWords)"
        if textModel != nil {
            self.textModel?.value = textView.text
        }
    }