码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-01-12 11:34:30      阅读:739      评论:0      收藏:0      [点我收藏+]

标签:

 

 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 }

 

运行结果:

 技术分享

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

标签:

原文地址:http://www.cnblogs.com/chenyuansheng/p/5123708.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!