ios开发同一个lab显示不同的颜色

闲来无事自己把自己学的东西发表出来供大家使用学习。

UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 30)];

    [self.view addSubview:lab];

    NSMutableAttributedString *textStr = [[NSMutableAttributedString alloc] initWithString:@"红色黄色的,黑色"];

    [textStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];//从0位置开始的长度为2的红色

    [textStr addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(2, 4)];//从2位置开始的长度为2的黄色的,

    [textStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(6, 2)];//从6位置开始的长度为2的黑色

    lab.attributedText = textStr;

原文地址:https://www.cnblogs.com/godlovexq/p/5054779.html