NSMutableAttributedString

NSMutableAttributedString

1.设置字符串中数字字符串的颜色:

// 设置字符串中数字的颜色
- (void)setTextColor:(UILabel *)label FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor
{
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:label.text]; NSCharacterSet* nonDigits =[[NSCharacterSet decimalDigitCharacterSet] invertedSet];
int remainSecond =[[label.text stringByTrimmingCharactersInSet:nonDigits] intValue];
NSLog(@" num %d ",remainSecond); NSString *labelText = label.text; for (int i = ; i < labelText.length; i ++) {
//这里的小技巧,每次只截取一个字符的范围
NSString *a = [labelText substringWithRange:NSMakeRange(i, )];
//判断装有0-9的字符串的数字数组是否包含截取字符串出来的单个字符,从而筛选出符合要求的数字字符的范围NSMakeRange
NSArray *number = @[@"",@"",@"",@"",@"",@"",@"",@"",@"",@""];
if ([number containsObject:a]) {
[str setAttributes:@{NSForegroundColorAttributeName:SELECT_PERSON_BUTTON_COLOR,NSFontAttributeName:FONT_13} range:NSMakeRange(i, )];
}
}
label.attributedText = str;
}

2.截取某个字符串段,设置字体颜色:

- (void)setBlueColorStringWithText:(NSMutableString *)text {

    NSRange startRange = [text rangeOfString:@"("];
NSRange endRange = [text rangeOfString:@")"];
NSRange range = NSMakeRange(startRange.location + startRange.length -1, endRange.location - startRange.location - startRange.length + 2);
NSDictionary *attribs = @{NSForegroundColorAttributeName: SELECT_PERSON_BUTTON_COLOR,
NSFontAttributeName:FONT_13
};
NSMutableAttributedString *textStr = [[NSMutableAttributedString alloc] initWithString:text];
[textStr setAttributes:attribs range:range];
self.deadlineLabel.attributedText = textStr;
}

  

04-13 23:21