iOS_字符串显示不同颜色
-
-
OS开发中经常会遇到这样的问题就是一个Label 中的文字需要两种以上的颜色现实
比如注册按钮下一般会有服务协议,这里的文字一般都会做区分
如下图
我们直接看代码
- UILabel *hintLabel=[[UILabel alloc]initWithFrame:CGRectMake(30, 120, 320, 66)];
- hintLabel.numberOfLines=0;
- [self.view addSubview:hintLabel];
- NSMutableAttributedString *hintString=[[NSMutableAttributedString alloc]initWithString:@"点击注册按钮即表示您已同意西游隐私条款和服务协议"];
- //获取要调整颜色的文字位置,调整颜色
- NSRange range1=[[hintString string]rangeOfString:@"西游隐私条款"];
- [hintString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:range1];
- NSRange range2=[[hintString string]rangeOfString:@"服务协议"];
- [hintString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range2];
- hintLabel.attributedText=hintString;
其实,就是使用到了NSMutableAttributedString 的功能,Label设置 attributedText就好了
-
-
-
-
-
最近写代码需要根据不同的内容显示不同的颜色。在这里mark一下。设置颜色:
12345NSString *contentStr = @
"简介:hello world"
;
NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:contentStr];
//设置:在0-3个单位长度内的内容显示成红色
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(
0
,
3
)];
label.attributedText = str;
实现效果:现在的项目有这么一个效果要实现:
如果所示,需要让数字显示成红色。问题是,有时候数字是2位数或者更多,给自己mark了一个方法: