UILabel高亮显示

搜索时,一般都需要在搜索结果中将搜索关键字进行高亮显示,于是就有了这个小东西。

1
2
3
4
5
6
7
8
9
#import <UIKit/UIKit.h>

@interface JTHighlightedLabel : UILabel

@property (nonatomic, strong) UIColor *highlightedColor;

- (void)setText:(NSString *)text hightlightText:(NSString *)highlightText;

@end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#import "JTHighlightedLabel.h"

@implementation JTHighlightedLabel

- (void)setText:(NSString *)text hightlightText:(NSString *)highlightText withColor:(UIColor *)highlightColor highlightFont:(UIFont *)highlightFont {
if (color == nil) {
highlightColor = [UIColor blueColor];
}
if (font == nil) {
highlightFont = self.font;
}

if (text.length == 0) {
return;
}

if (highlightText.length == 0) {
self.text = text;
return;
}

NSMutableAttributedString *mutableAttributedStr = [[NSMutableAttributedString alloc] initWithString:text];
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];
}
}
self.attributedText = mutableAttributedStr;
}
@end