iOS Label显示不同颜色和字体

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_22080737/article/details/78557407

开发中,我们经常会遇到一行字,但是显示不同颜色和字体的情况,话不多说,直接上代码。

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;

以上两种方式效果图如下:

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_22080737/article/details/78557407
今日推荐