直接代码
NSString * str=@"fjsalfasdfdasfasdjf我很好";
NSMutableAttributedString * attriStr=[[NSMutableAttributedString alloc]initWithString:str];
NSRange range = [str rangeOfString:@"我很好"];
[attriStr addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} range:range];
UILabel * label=[[UILabel alloc]initWithFrame:CGRectMake(10, 100, 300, 100)];
label.attributedText=attriStr;
[self.view addSubview:label];
好出来效果是
多个keyword用这个方法
<pre name="code" class="objc"> NSError *error;
NSString *strRegex = keyWord;
NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:strRegex options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:&error];
//无视大小写.
NSArray *matches =[reg matchesInString:tempStr options:NSMatchingReportProgress range:NSMakeRange(0, tempStr.length)];
for (NSTextCheckingResult *match in matches)
{
NSRange range = [match range];
[tempAttriStr addAttribute:NSForegroundColorAttributeName value:[UMComTools colorWithHexString:FontColorBlue] range:range];
}
该博客介绍了如何在Objective-C(OC)中为NSString设置关键字颜色,通过代码实现字符串中特定关键字的高亮显示,使得关键字在文本中凸显出来。
3880

被折叠的 条评论
为什么被折叠?



