监听 限制 TextView 字数的正确姿势

swift

//MARK: - TextViewDelegate
func textViewDidChange(_ textView: UITextView) {
//获得已输出字数与正输入字母数
    let selectRange = textView.markedTextRange
    //获取高亮部分 - 如果有联想词则解包成功
     if let selectRange = selectRange {
            let position =  textView.position(from: (selectRange.start), offset: 0)
                if (position != nil) {
                    return
                }
            }
                let textContent = textView.text
                let textNum = textContent?.characters.count
            //截取
            if textNum! > 50 {
                let index = textContent?.index((textContent?.startIndex)!, offsetBy: 50)
                let str = textContent?.substring(to: index!)
                textView.text = str
thisContentNumLabel.text = 50/50

            }
thisContentNumLabel.text = String(format: "%ld/50",textView.text.characters.count)

    }

OC

- (void)textViewDidChange:(UITextView *)textView{

    UITextRange *selectedRange = [textView markedTextRange];
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    
    //如果在变化中是高亮部分在变,就不要计算字符了
    if (selectedRange && pos) {
        return;
    }
    int length = (int)textView.text.length;
    if (length>50) {
        textView.text = [textView.text substringToIndex:50];
   self.textLengthLabel.text  = 50/50;
    }else{
        self.textLengthLabel.text = [NSString stringWithFormat:@"%d/%d",length,50];
    }
}

你可能感兴趣的:(监听 限制 TextView 字数的正确姿势)