mirror of
https://github.com/NohamR/knowledge-kit.git
synced 2026-05-25 04:17:17 +00:00
docs: 批量博文
This commit is contained in:
39
Chapter1 - iOS/1.28.md
Normal file
39
Chapter1 - iOS/1.28.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# UILabel 给关键字模糊匹配并高亮
|
||||
|
||||
> 有些情况就是需要查找某个字符串并高亮,但有些需求就是需要全局模糊查找,找到符合的字符串并高亮。造了个小轮子
|
||||
|
||||
###效果图
|
||||

|
||||
|
||||
```
|
||||
#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:NSLiteralSearch 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;
|
||||
}
|
||||
```
|
||||
|
||||
[源码地址](https://github.com/FantasticLBP/BlogDemos/tree/master/LBPAttributedStringTools)
|
||||
Reference in New Issue
Block a user