iOS UITextView编辑中添加话题,比如将两个"#"号之间的字体变为蓝色

有时候需要在UITextView编辑的时候实时监听文本实现将两个“#”号之间的文字变蓝(话题)

//UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView

{

if (textView.markedTextRange == nil) {

NSString *topicPattern = @"#[^#]+#";

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:topicPattern options:0 error:nil];

NSRange range = NSMakeRange(0, textView.attributedText.length);

NSArray *results = [regex matchesInString:textView.attributedText.string options:0 range:range];

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:textView.attributedText.string];

[attributedString addAttributes:@{NSFontAttributeName:sysFont(16)} range:range];

for (NSTextCheckingResult *result in results) {

[attributedString addAttributes:@{NSForegroundColorAttributeName :colorConversion(@"507daf"),NSFontAttributeName:sysFont(16)} range:result.range];

}

NSRange rg = textView.selectedRange;

if (rg.location == NSNotFound) {

rg.location = textView.text.length;

}

textView.attributedText = attributedString;

textView.selectedRange = NSMakeRange(rg.location, 0);

}

}

特别需要注意的是当你用正则校验之后每次重新给UITextView赋值之后会改动会将光标置为最后的位置,所以当你编辑中间的文字时候每编辑一次光标就会移动到最后 ,要解决这个问题就需要每次记录光标的位置,赋值之后重新将光标的位置变回来,即:

NSRange rg = textView.selectedRange;

if (rg.location == NSNotFound) {

rg.location = textView.text.length;

}

textView.attributedText = attributedString;

textView.selectedRange = NSMakeRange(rg.location, 0);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容