NSAttributedString几个用法

来源:互联网 发布:java期末考试题库 编辑:程序博客网 时间:2024/05/29 04:36
一:设定label的颜色// 1.设置字符串NSString *string = @"我是label";// 2.富文本属性NSMutableDictionary *attrs = [NSMutableDictionary dictionary];attrs[NSForegroundColorAttributeName] = [UIColor redColor];attrs[NSFontAttributeName] = [UIFont systemFontOfSize:12];// 3.设置富文本属性字符// 注意:它是继承至NSObject的NSAttributedString *str = [[NSAttributedString alloc] initWithString:stringattributes:attrs];// 4.给labal的富文本属性赋值self.attrLabel.attributedText = str; 二:实现分段字体设置,每个字段都可以分别设置它们的属性NSMutableAttributedString *strM = [[NSMutableAttributedString alloc] initWithString:@"我们中国共产党"];NSMutableDictionary *attrs1 = [NSMutableDictionary dictionary];attrs1[NSForegroundColorAttributeName] = [UIColor redColor];NSMutableDictionary *attrs2 = [NSMutableDictionary dictionary];attrs2[NSForegroundColorAttributeName] = [UIColor yellowColor];NSMutableDictionary *attrs3 = [NSMutableDictionary dictionary];attrs3[NSForegroundColorAttributeName] = [UIColor greenColor];[strM setAttributes:attrs1 range:NSMakeRange(0, 2)];[strM setAttributes:attrs2 range:NSMakeRange(2, 2)];[strM setAttributes:attrs3 range:NSMakeRange(4, 2)];self.attrLabel.attributedText = strM;三:实现图文混排// 1.创建可变的属性字符(必须是可变的)NSMutableAttributedString *strM = [[NSMutableAttributedString alloc] initWithString:@"我们中国共产党"];// 2.创建一个附件NSTextAttachment *attach = [[NSTextAttachment alloc] init];// 3.附件添加一个imageattach.image = [UIImage imageNamed:@"1"];// 4.设定image的尺寸attach.bounds = CGRectMake(0, 0, 20, 20);// 5.根据附件创建一个富文本属性字符串NSAttributedString *strM1 = [NSMutableAttributedString attributedStringWithAttachment:attach];// 6.添加到可变的属性字符串中[strM appendAttributedString:strM1];// 7.赋值给label的attributedText属性self.attrLabel.attributedText = strM;
0 0
原创粉丝点击