测试代码:
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];
//方法
//设置文本(label)文字中某一段文字(从开头到word,word为一个字符或者一个字)的颜色为color
void SetLabelTextColorToStr(UILabel *label,UIColor *color,NSString *word){
NSMutableAttributedString *newStr = [[NSMutableAttributedStringalloc] initWithString:label.text];
NSRange Range =NSMakeRange(0, [[newStrstring] rangeOfString:word].location+1);
[newStr addAttribute:NSForegroundColorAttributeNamevalue:color range:Range];
[label setAttributedText:newStr] ;
}