有時(shí)候需要在UITextView編輯的時(shí)候?qū)崟r(shí)監(jiān)聽(tīng)文本實(shí)現(xiàn)將兩個(gè)“#”號(hào)之間的文字變藍(lán)(話題)
//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);
}
}
特別需要注意的是當(dāng)你用正則校驗(yàn)之后每次重新給UITextView賦值之后會(huì)改動(dòng)會(huì)將光標(biāo)置為最后的位置,所以當(dāng)你編輯中間的文字時(shí)候每編輯一次光標(biāo)就會(huì)移動(dòng)到最后 ,要解決這個(gè)問(wèn)題就需要每次記錄光標(biāo)的位置岂昭,賦值之后重新將光標(biāo)的位置變回來(lái)询一,即:
NSRange rg = textView.selectedRange;
if (rg.location == NSNotFound) {
rg.location = textView.text.length;
}
textView.attributedText = attributedString;
textView.selectedRange = NSMakeRange(rg.location, 0);