设定标签以#开始和空格结尾,在输入框中实现标签以高亮颜色显示。如果使用textView.attributedText来设定高亮颜色的话,会导致中文输入异常。
使用textView.textStorage可以实现正常显示和输入。
- (void)textViewDidChange:(UITextView *)textView {
if (textView.text.length>0) {
[textView.textStorage addAttributes:@{NSForegroundColorAttributeName:kTextColor} range:NSMakeRange(0, textView.text.length)];
NSString *content = textView.text;
NSInteger iLocation = 0;
while (true) {
NSRange r = [content rangeOfString:@"(#.*? )" options:NSRegularExpressionSearch range:NSMakeRange(iLocation, content.length-iLocation)];
if (r.location == NSNotFound) {
break;
}
[textView.textStorage addAttributes:@{NSForegroundColorAttributeName:kMarkColor} range:r];
iLocation = r.location+r.length;
}
}
}