前言
當我們項目中有要遍歷一段字符串,找出需要高亮顯示的文字的情況中,有時候這段字符會包含一樣的字符,這時候就會出現問題了。
-(void)test{
//假數據,這里只用來測試,真實數據情況下就用model模型了,見諒!!
NSDictionary *dic1 = @{@"type":@"0",@"content":@"訂單"};
NSDictionary *dic2 = @{@"type":@"3",@"content":@"測試跳轉"};
NSDictionary *dic3 = @{@"type":@"0",@"content":@"還未反饋,廣告主"};
NSDictionary *dic4 = @{@"type":@"8",@"content":@"差一點是帥哥"};
NSDictionary *dic5 = @{@"type":@"0",@"content":@"提醒你快去"};
NSDictionary *dic6 = @{@"type":@"9",@"content":@"反饋"};
NSDictionary *dic7 = @{@"type":@"0",@"content":@"哦!"};
// 添加到總得數據源數組
???? NSMutableArray * array = [[NSMutableArray alloc]initWithObjects:dic1,dic2,dic3,dic4,dic5,dic6,dic7,nil];
// 拼接字符串
??? NSMutableArray *strArr =[NSMutableArray arrayWithCapacity:0];
????? for (NSDictionary *dicttion in array) {
???? [strArr addObject:dicttion[@"content"]];
??????  }
????_pinChuan3 = [strArr componentsJoinedByString:@""];
//設置attributed
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:_pinChuan3];
// 字體大小
text.font = [UIFont boldSystemFontOfSize:16.0f];
// 設置行間距
text.lineSpacing = 5;
__weak typeof(self) weakSelf = self;
__block NSString * content1;
//遍歷查找字符串
[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
??? NSDictionary * dict = obj;
??? if ([dict[@"type"] integerValue] !=0) {
??? content1 = dict[@"content"];
??? //找range
??? NSRange range = [_pinChuan3 rangeOfString:content1];
??? [text setTextHighlightRange:range color:[UIColor redColor] backgroundColor:[UIColor clearColor] userInfo:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
???? NSLog(@"點擊");
???? [weakSelf didSelectedDic:dict];//點擊高度文字操作
?? } longPressAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
???? NSLog(@"長按");
???? }];
??? }
?? }];
// Set to YYLabel or YYTextView.
??? YYLabel *label = [YYLabel new];
??? CGFloat Height = [self getterSpaceLabelHeight:_pinChuan3 withLineSpacing:5 withFont:[UIFont systemFontOfSize:16.0f] withWidth:KScreenWidth - 40];
??? label.frame = CGRectMake(20, 300,KScreenWidth - 40, Height);
??? label.attributedText = text;
??? label.numberOfLines = 0;
??? label.font = [UIFont systemFontOfSize:16.0f];
??? label.backgroundColor = [UIColor lightGrayColor];
??? [label sizeToFit];
??? [self.view addSubview:label];
}
這這段代碼中,其實我們想要顯示高亮狀態字符,重要的就是查找需要高亮顯示的文字range了,看看官方文檔里給的幾個查找range的方法吧
我的查找方法,就是用的文檔里面的第一個方法,顯然,在對于有重復字符串情況下,就不那么好使了。
重點來了!!!用這個方法,從后往前取需要匹配的string 記錄range,然后更新searchRange.
-
-(NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask;
來看看NSStringCompareOptions的枚舉里面的都代表什么吧
這里的官方給的注釋也很明確了,上述方法里面找到 range
NSRange range = [_pinChuan3 rangeOfString:content1 options:NSBackwardsSearch];
然后再次運行
沒毛病! 解決!
??????github地址,點擊下載Demo