UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0,60, 150, 30)];
label.text=@"你好helloworld";
label.backgroundColor=[UIColor lightGrayColor];
NSMutableAttributedString *attriString=[[NSMutableAttributedString alloc] 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:NSForegroundColorAttributeName value:[UIColor redColor] range:range1];
[attriString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor]range:range2];
label.attributedText=attriString;
[self.view addSubview:label];
UIButton *button = [[UIButton alloc] init];
button.frame=CGRectMake(0,120, 150, 50);
[button setTitle:@"你好视界"forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor lightGrayColor]];
NSMutableAttributedString *btnAttStr=[[NSMutableAttributedString alloc] initWithString:button.titleLabel.text];
NSRange btnRange=NSMakeRange(0,2);//设置你好是绿色
NSRange btnR=NSMakeRange(2,2); //设置视界是红色
[btnAttStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor]range:btnRange];
[btnAttStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:btnR];
[button setAttributedTitle:btnAttStr forState:UIControlStateNormal];
[self.view addSubview:button];
[_tiankuanBtn setTitle:@"注册表示已同意《隐私条款以及服务协议》" forState:UIControlStateNormal];
NSMutableAttributedString *btnAttStr=[[NSMutableAttributedString alloc] initWithString:_tiankuanBtn.titleLabel.text];
NSRange btnRange=NSMakeRange(0,7);//设置你好是绿色
NSRange btnR=NSMakeRange(7,12); //设置视界是红色
[btnAttStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor]range:btnRange];
[btnAttStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:btnR];
[_tiankuanBtn setAttributedTitle:btnAttStr forState:UIControlStateNormal];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"注册表示已同意《隐私条款以及服务协议》"];
NSRange strRange = {7,12};
[str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
[_tiankuanBtn setAttributedTitle:str forState:UIControlStateNormal];