2019-01-07

    
    NSString *textStr = @"我有一个梦想,先挣他一个亿;我有一个梦想,先活他一百年;我有一个梦想,先放荡他一回;我有一个梦想,去一个没人的地方。";
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:textStr attributes:@{}];
    
//    [attStr addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} range:[textStr rangeOfString:@"梦想"]];
    /// 这个也可以做 正则表达式 匹配么
//    NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:@"梦想" options:0 error:nil];
//    NSArray* match = [reg matchesInString:textStr options:0 range:NSMakeRange(0, [textStr length])];
//    for (NSTextCheckingResult *result in match) {
//        NSLog(@"%@",NSStringFromRange(result.range));
//        [attStr addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} range:result.range];
//    }
    
    NSString *yige = @"想活";
    for (int i = 0; i < yige.length; i++) {
        NSRange rang = NSMakeRange(i, 1);
        NSString *str = [yige substringWithRange:rang];
        
        ///匹配一段字符一遍
        [attStr addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} range:[textStr rangeOfString:str]];
        
        ///匹配所有字符
//        NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:str options:0 error:nil];
//        NSArray* match = [reg matchesInString:textStr options:0 range:NSMakeRange(0, [textStr length])];
//        for (NSTextCheckingResult *result in match) {
//            NSLog(@"%@",NSStringFromRange(result.range));
//            [attStr addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} range:result.range];
//        }
        
    }
    tintLB.attributedText = attStr.copy;
    
    

你可能感兴趣的:(2019-01-07)