有时候需要在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);