UILabel *label=[[UILabelalloc] initWithFrame:CGRectMake(0,60, 150, 30)];
label.text=@"你好helloworld";
label.backgroundColor=[UIColorlightGrayColor];
NSMutableAttributedString *attriString=[[NSMutableAttributedStringalloc] initWithString:label.text];
NSRange range1=NSMakeRange(0,3);//设置从第1个到底4个显示红色 location是0 长度是3
NSRange range2=NSMakeRange(4,2);//设置第5和第6两个显示绿色 Location是4 长度是2
NSLog(@"label.text length is %d ",label.text.length);
//第一个字
[attriString addAttribute:NSForegroundColorAttributeNamevalue:[UIColorredColor] range:range1];
[attriString addAttribute:NSForegroundColorAttributeNamevalue:[UIColorgreenColor]range:range2];
label.attributedText=attriString;
[self.viewaddSubview:label];
UIButton *button = [[UIButtonalloc] init];
button.frame=CGRectMake(0,120, 150, 50);
[button setTitle:@"你好视界"forState:UIControlStateNormal];
[button setBackgroundColor:[UIColorlightGrayColor]];
NSMutableAttributedString *btnAttStr=[[NSMutableAttributedStringalloc] initWithString:button.titleLabel.text];
NSRange btnRange=NSMakeRange(0,2);//设置你好是绿色
NSRange btnR=NSMakeRange(2,2); //设置视界是红色
[btnAttStr addAttribute:NSForegroundColorAttributeNamevalue:[UIColorgreenColor]range:btnRange];
[btnAttStr addAttribute:NSForegroundColorAttributeNamevalue:[UIColorredColor] range:btnR];
[button setAttributedTitle:btnAttStr forState:UIControlStateNormal];
[self.viewaddSubview:button];