AttributedString - 富文本 - 属性字符串(不同字体大小颜色,下划线中划线)

   在实际开发中,有时候需要在一个Label内,同时存在不同的字体/颜色/字体大小我们可以称这种文本叫『富文本』,可以通过设置Label的属性字符串来达到要求。

  基本思路:

  (NSMutableAttributedString *)attributedString = [[NSMutableAttributedString alloc]initWithString:string];

  label.attributedText = attributedString;

  

 1 #import "ViewController.h"
 2 
 3 @interface ViewController ()
 4 
 5 @end
 6 
 7 @implementation ViewController
 8 
 9 - (void)viewDidLoad {
10     [super viewDidLoad];
11     // Do any additional setup after loading the view, typically from a nib.
12 
13     NSArray *array = @[@"小明:吃饭了吗?",
14                        @"我:吃过了.",
15                        @"小明:吃饭了吗?",
16                        @"我:吃过了."
17                        ];
18 
19     for (int i = 0; i < array.count; i++)
20     {
21         UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(20, 60+30*i, 300, 20)];
22         //l.text = array[i];
23         [self.view addSubview:l];
24         
25         //设置属性字符串
26         l.attributedText = [self attributeTextWithString:array[i]];
27     }
28     
29     [self testStrikethrough];
30     
31 }
32 
33 #pragma mark - 一个label显示不同的颜色,不同字体大小
34 - (NSMutableAttributedString *)attributeTextWithString:(NSString *)string
35 {
36     NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:string];
37     
38     //找名字和内容的分割符
39     NSRange range = [string rangeOfString:@":"];
40     
41     //添加属性:颜色 大小
42     [attributeString addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor],NSFontAttributeName:[UIFont systemFontOfSize:25]} range:NSMakeRange(0, range.location)];
43     
44     return attributeString;
45 }
46 
47 #pragma mark - 设置中划线和下划线
48 - (void)testStrikethrough
49 {
50     UILabel *mutLine = [[UILabel alloc] initWithFrame:CGRectMake(20, 200, 300, 200)];
51     //设置属性文字
52     mutLine.attributedText = [self strikethroughlineString:@"AttributedString - 富文本(不同字体大小颜色,下划线中划线)"];
53     mutLine.numberOfLines = 0;
54     [self.view addSubview:mutLine];
55 }
56 
57 #pragma mark - 添加中划线
58 - (NSMutableAttributedString *)strikethroughlineString:(NSString *)string
59 {
60     /*
61      NSStrikethroughStyleAttributeName 中划线
62      NSStrikethroughColorAttributeName 中划线的颜色
63      NSUnderlineStyleAttributeName 下划线
64      */
65     /*
66      NSUnderlineStyleSingle 单线
67      NSUnderlineStyleThick 加粗
68      NSUnderlineStyleDouble 双线
69      */
70     NSMutableAttributedString *attributeText = [[NSMutableAttributedString alloc] initWithString:string attributes:@{NSUnderlineStyleAttributeName:@(NSUnderlineStyleDouble),NSUnderlineColorAttributeName:[UIColor redColor]}];
71     
72     return attributeText;
73 }

 

运行结果:

 

posted on 2016-01-12 11:11  Wilson_CYS  阅读(1099)  评论(0编辑  收藏  举报

导航