开发中有些UI经常会出现同一段话显示颜色不一致的情况,在没有好办法的情况下我们会用两个label来实现,但是这样的话适配起来并不方便,这里我有一种方法跟大家分享一下:

UILabel* noteLabel = [[UILabel alloc] init];
noteLabel.frame = CGRectMake(60, 100, 200, 100);
noteLabel.textColor = [UIColor blackColor];
noteLabel.numberOfLines = 2;


NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:@"注册:同意"];
NSRange redRange = NSMakeRange([[noteStr string] rangeOfString:@"注册:"].location, [[noteStr string] rangeOfString:@"注册:"].length);
[noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:redRange];

NSRange redRangeTwo = NSMakeRange([[noteStr string] rangeOfString:@"同意"].location, [[noteStr string] rangeOfString:@"同意"].length);
[noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:redRangeTwo];

[noteLabel setAttributedText:noteStr];
[noteLabel sizeToFit];
[self.view addSubview:noteLabel];

也可到我的github去下载代码:​​https://github.com/codeliu6572/Label-different-color​