字符串中关键字高亮

// 高亮显示字符串中的关键字
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.title];
    
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:self.keyword options:0 error:&error];
    NSArray *matches = [regex matchesInString:self.title
                                      options:0
                                        range:NSMakeRange(0, self.title.length)];
    
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, [attributedString length])];
    for (NSTextCheckingResult *match in matches)
    {
        NSRange matchRange = [match rangeAtIndex:0];
        [attributedString addAttribute:NSForegroundColorAttributeName
                                 value:[UIColor colorWithHexString:@"ff6e11"]
                                 range:matchRange];
    }
//UILabel self.titleLbl.attributedText
= attributedString;
原文地址:https://www.cnblogs.com/allanliu/p/4778357.html