有些狀況就是須要查找某個字符串並高亮,但有些需求就是須要全局模糊查找,找到符合的字符串並高亮。造了個小輪子git
#pragma mark -- 設置在一個文本中全部特殊字符的特殊顏色
+ (NSMutableAttributedString *)setAllText:(NSString *)allStr andSpcifiStr:(NSString *)keyWords withColor:(UIColor *)color specifiStrFont:(UIFont *)font{
NSMutableAttributedString *mutableAttributedStr = [[NSMutableAttributedString alloc] initWithString:allStr];
if (color == nil) {
color = [UIColor redColor];
}
if (font == nil) {
font = [UIFont systemFontOfSize:17];
}
for (NSInteger j=0; j<=keyWords.length-1; j++) {
NSRange searchRange = NSMakeRange(0, [allStr length]);
NSRange range;
NSString *singleStr = [keyWords substringWithRange:NSMakeRange(j, 1)];
while
((range = [allStr rangeOfString:singleStr options:0 range:searchRange]).location != NSNotFound) {
//改變屢次搜索時searchRange的位置
searchRange = NSMakeRange(NSMaxRange(range), [allStr length] - NSMaxRange(range));
//設置富文本
[mutableAttributedStr addAttribute:NSForegroundColorAttributeName value:color range:range];
[mutableAttributedStr addAttribute:NSFontAttributeName value:font range:range];
}
}
return mutableAttributedStr;
}
複製代碼
源碼地址github