改变字符串中指定字符的颜色

来源:互联网 发布:lnmp 查看php日志 编辑:程序博客网 时间:2024/05/30 05:13

有的时候我们有这样的需求:一行字符串中的字符需要显示不同的颜色,这时候 我们就需要指定特定的字符显示特定的颜色

- (void)viewDidLoad {NSMutableAttributedString *gitStr = [self ChangeStrColor:[Util IncreaseDecimal:@"不同颜色的字符组成的字符串显示"] Loction:5];label.attributedText = gitStr;}- (NSMutableAttributedString *)ChangeStrColor:(NSString *)ColorStr Loction:(NSInteger)loction {    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:ColorStr];    NSInteger lengh = [str length];    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,loction)];    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(lengh-3,3)];    return str;}
0 0