一开始采用的方法是函数textView:shouldChangeTextInRange:replacementText:来进行判断:
//键入Done时,插入换行符,然后执行addBookmark - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { //判断加上输入的字符,是否超过界限 NSString *str = [NSString stringWithFormat:@"%@%@", textView.text, text]; if (str.length > BOOKMARK_WORD_LIMIT) { textView.text = [textView.text substringToIndex:BOOKMARK_WORD_LIMIT]; return NO; } return YES; } |
但在使用中发现该方法在有联想输入的时候,根本无法对联想输入的词进行判断,然后尝试使用textViewDidChange:,验证可行:
#define MaxNumberOfDescriptionChars 100//textview最多输入的字数
/*由于联想输入的时候,函数textView:shouldChangeTextInRange:replacementText:无法判断字数, 因此使用textViewDidChange对TextView里面的字数进行判断 */ - (void)textViewDidChange:(UITextView *)textView { UITextRange *selectedRange = [textView markedTextRange]; //获取高亮部分 UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0]; //如果在变化中是高亮部分在变,就不要计算字符了 if (selectedRange && pos) { return; } //该判断用于联想输入 if (textView.text.length > MaxNumberOfDescriptionChars) { textView.text = [textView.text substringToIndex:MaxNumberOfDescriptionChars]; } //还可输入的字数 self.countLabel.text=[NSString stringWithFormat:@"%lu",MaxNumberOfDescriptionChars-textView.text.length]; } |