swift
//MARK: - TextViewDelegate
func textViewDidChange(_ textView: UITextView) {
//獲得已輸出字?jǐn)?shù)與正輸入字母數(shù)
let selectRange = textView.markedTextRange
//獲取高亮部分 - 如果有聯(lián)想詞則解包成功
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];
//如果在變化中是高亮部分在變颠放,就不要計(jì)算字符了
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];
}
}