改变字符start 和 end 之间的字符的颜色 和 字体大小

+ (void)messageAction:(UILabel*)theLab startString:(NSString *)start endString:(NSString *)end andAllColor:(UIColor *)allColor
    andMarkColor:(UIColor *)markColor andMarkFondSize:(float)fontSize andParagraphStyle:(NSMutableParagraphStyle*)paragraphStyle  {
    NSString *tempStr = theLab.text;
    NSRange allrange = NSMakeRange(0, [tempStr length]);
    NSMutableAttributedString *strAtt = [[NSMutableAttributedString alloc] initWithString:tempStr];
    if (paragraphStyle == nil) {
        paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    }
    [strAtt addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [tempStr length])];
    
//    [strAtt addAttribute:NSForegroundColorAttributeName value:allColor range:NSMakeRange(0, [strAtt length])];
    // 'x''y'字符的范围   // 为了删除这个字符 添加包含判断
    
    NSUInteger count = 0, length = [tempStr length];
    NSRange range = NSMakeRange(0, length);
    while(range.location != NSNotFound)
    {
        range = [tempStr rangeOfString: start options:0 range:range];
        if(range.location != NSNotFound)
        {
            range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
            count++;
        }
    }
    
    
    NSRange tempRange = NSMakeRange(0, [start length]);
    NSRange tempRangeOne = NSMakeRange(0, [end length]);
    for (int i = 0; i < count; i ++) {
        
        if ([self judgeStringIsNull:start] && [tempStr containsString:start] && [tempStr containsString:end]) {
            tempRange = [tempStr rangeOfString:start options:0 range:allrange];
        }
        
        if ([self judgeStringIsNull:end] && [tempStr containsString:end] && [tempStr containsString:start]) {
            tempRangeOne =  [tempStr rangeOfString:end options:0 range:allrange];
        }
        
        
        [strAtt replaceCharactersInRange:tempRangeOne withString:@""];
        [strAtt replaceCharactersInRange:tempRange withString:@""];
        
        
        tempStr = [tempStr stringByReplacingCharactersInRange:tempRangeOne withString:@""];
        tempStr = [tempStr stringByReplacingCharactersInRange:tempRange withString:@""];
        
        // 更改字符颜色
        NSRange markRange = NSMakeRange(tempRange.location, tempRangeOne.location-(tempRange.location + tempRange.length));
        [strAtt addAttribute:NSForegroundColorAttributeName value:markColor range:markRange];
        // 更改字体
        //     [strAtt addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:20]
        range:NSMakeRange(0, [strAtt length])];
        [strAtt addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:fontSize] range:markRange];
        

        

        allrange = NSMakeRange(0 , [tempStr length]);
        
    }
        // 删除x y

    theLab.attributedText = strAtt;
}



oc 字符串

你可能感兴趣的:(改变字符start 和 end 之间的字符的颜色 和 字体大小)