iOS UITextView編輯中添加話題,比如將兩個"#"號之間的字體變?yōu)樗{(lán)色

有時候需要在UITextView編輯的時候?qū)崟r監(jiān)聽文本實(shí)現(xiàn)將兩個“#”號之間的文字變藍(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)你用正則校驗之后每次重新給UITextView賦值之后會改動會將光標(biāo)置為最后的位置,所以當(dāng)你編輯中間的文字時候每編輯一次光標(biāo)就會移動到最后 ,要解決這個問題就需要每次記錄光標(biāo)的位置,賦值之后重新將光標(biāo)的位置變回來,即:

NSRange rg = textView.selectedRange;

if (rg.location == NSNotFound) {

rg.location = textView.text.length;

}

textView.attributedText = attributedString;

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容