开发中,我们经常会遇到一行字,但是显示不同颜色和字体的情况,话不多说,直接上代码。
1、显示不同颜色,有两种方式
(1)通过 range 来设置
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"点击代表您已阅读并同意用户规则和协议"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0,11)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(11,4)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(16,2)];
label.attributedText = str;
(2)通过文字来设置
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"点击代表您已阅读并同意用户规则和协议"];
NSRange range1 = [[str string] rangeOfString:@"点击代表您已阅读并同意"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:range1];
NSRange range2 = [[str string] rangeOfString:@"用户规则"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range2];
NSRange range3 = [[str string] rangeOfString:@"协议"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range3];
label.attributedText = str;
以上两种的效果一样,如图:
2、显示不同字体,也是两种方式
(1)通过 range 来设置
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:13.0] range:NSMakeRange(0, 11)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14.0] range:NSMakeRange(11, 4)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:14.0] range:NSMakeRange(16, 2)];
label.attributedText = str;
(2)通过文字来设置
NSRange range1 = [[str string] rangeOfString:@"点击代表您已阅读并同意"];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:13.0] range:range1];
NSRange range2 = [[str string] rangeOfString:@"用户规则"];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14.0] range:range2];
NSRange range3 = [[str string] rangeOfString:@"协议"];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:14.0] range:range3];
label.attributedText = str;
以上两种方式效果图如下:
网友评论