swift UILable 文字颜色分段

来源:互联网 发布:ar卡片制作软件 编辑:程序博客网 时间:2024/05/16 00:50

iOS开发中经常会遇到这样的问题就是一个Label 中的文字需要两种以上的颜色现实

比如注册按钮下一般会有服务协议,这里的文字一般都会做区分

如下图


我们直接看代码

[objc] view plaincopy
  1. UILabel *hintLabel=[[UILabel alloc]initWithFrame:CGRectMake(3012032066)];  
  2.     hintLabel.numberOfLines=0;  
  3.     [self.view addSubview:hintLabel];  
  4.       
  5.     NSMutableAttributedString *hintString=[[NSMutableAttributedString alloc]initWithString:@"点击注册按钮即表示您已同意西游隐私条款和服务协议"];  
  6.     //获取要调整颜色的文字位置,调整颜色  
  7.     NSRange range1=[[hintString string]rangeOfString:@"西游隐私条款"];  
  8.     [hintString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:range1];  
  9.       
  10.     NSRange range2=[[hintString string]rangeOfString:@"服务协议"];  
  11.     [hintString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range2];  
  12.       
  13.     hintLabel.attributedText=hintString;  

其实,就是使用到了NSMutableAttributedString   的功能,Label设置 attributedText就好了
0 0
原创粉丝点击