zl程序教程

您现在的位置是:首页 >  其他

当前栏目

UITextView实现输入标签高亮

输入 实现 标签 高亮
2023-09-11 14:14:25 时间

设定标签以#开始和空格结尾,在输入框中实现标签以高亮颜色显示。如果使用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;
        }
    }
}