NSString设置关键字颜色 凸显关键字

直接代码

    NSString * str=@"fjsalfasdfdasfasdjf我很好";
    
    NSMutableAttributedString * attriStr=[[NSMutableAttributedString alloc]initWithString:str];
    NSRange range = [str rangeOfString:@"我很好"];
    [attriStr addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} range:range];
 
    UILabel * label=[[UILabel alloc]initWithFrame:CGRectMake(10, 100, 300, 100)];
    label.attributedText=attriStr;
    [self.view addSubview:label];
    

好出来效果是


多个keyword用这个方法

        NSError *error;
        NSString *strRegex = keyWord;
        NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:strRegex options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:&error];
        
        //无视大小写.
        NSArray *matches =[reg matchesInString:tempStr options:NSMatchingReportProgress range:NSMakeRange(0, tempStr.length)];
        
        for (NSTextCheckingResult *match in matches)
        {
            NSRange range = [match range];
            [tempAttriStr addAttribute:NSForegroundColorAttributeName value:[UMComTools colorWithHexString:FontColorBlue] range:range];
        }


 
  

你可能感兴趣的:(UI控件)