美文网首页
检索关键字并替换全部

检索关键字并替换全部

作者: 从容到没边的优雅 | 来源:发表于2021-06-10 13:28 被阅读0次
    /// 只要包含有搜索关键字都要高亮
    - (void)searchKeyHighlight:(NSString *)key {
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:_contenL.text];
        NSMutableAttributedString *attriKey = [[NSMutableAttributedString alloc] initWithString:key attributes:@{NSForegroundColorAttributeName: cc_green}];
        // 法1
    //    NSArray <NSString *>*arr = [str.string componentsSeparatedByString:key];
    //    NSInteger i = 0;
    //    NSRange range;
    //    while (i<arr.count-1) {
    //        if (i>0) {
    //            range = NSMakeRange(range.location + key.length + arr[i].length, key.length);
    //        } else {
    //            range = NSMakeRange(arr[i].length, key.length);
    //        }
    //        [str replaceCharactersInRange:range withAttributedString:attriKey];
    //        i++;
    //    }
    //    _contenL.attributedText = str;
        
        // 法2
        [str.string enumerateRegexMatches:key options:NSRegularExpressionCaseInsensitive usingBlock:^(NSString * _Nonnull match, NSRange matchRange, BOOL * _Nonnull stop) {
            [str replaceCharactersInRange:matchRange withAttributedString:attriKey];
        }];
        _contenL.attributedText = str;
    }
    

    相关文章

      网友评论

          本文标题:检索关键字并替换全部

          本文链接:https://www.haomeiwen.com/subject/cbbueltx.html