有些情況就是需要查詢某個字串並高亮,但有些需求就是需要全域性模糊查詢,找到符合的字串並高亮。造了個小輪子
效果圖
#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;
}
複製程式碼