美文网首页
【iOS】富文本

【iOS】富文本

作者: 修炼一颗真心 | 来源:发表于2017-03-01 11:18 被阅读0次

开发过程中经常会有一段文字显示不同大小和颜色的字体,或者给几个文字添加删除线或删除线,这种情况就可以用AttributedString来解决。

AttributedString具体用法

1.给控件赋值

普通的lable,button,textView等UI控件都有text这个属性显示普通文本,如果要去显示富文本,要使用他们的attributedText这个属性赋值

2.常用到的常量

1> NSFontAttributeName(字体)
该属性所对应的值是一个 UIFont 对象。

2> NSParagraphStyleAttributeName(段落)
该属性所对应的值是一个 NSParagraphStyle 对象

3>NSForegroundColorAttributeName(字体颜色)
该属性所对应的值是一个 UIColor 对象。

4> NSBackgroundColorAttributeName(字体背景色)
该属性所对应的值是一个 UIColor 对象。

5> NSKernAttributeName(字间距)
该属性所对应的值是一个 NSNumber 对象(整数)。

6> NSShadowAttributeName(阴影)
该属性所对应的值是一个 NSShadow 对象。默认为 nil。

7> NSStrikethroughStyleAttributeName(删除线)
该属性所对应的值是一个 NSNumber 对象(整数)。该值指定是否在文字上加上删除线

8> NSUnderlineStyleAttributeName(下划线)
该属性所对应的值是一个 NSNumber 对象(整数)。

3.初始化

1> - (id)initWithString:(NSString *)str;

2> - (id)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;

4.使用方法

为某一范围内文字设置多个属性

1> - (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;

为某一范围内文字添加某个属性

2> - (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;

为某一范围内文字添加多个属性

3> - (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;

移除某范围内的某个属性

4> - (void)removeAttribute:(NSString *)name range:(NSRange)range;

5.使用实例

UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 200, 30)];
testLabel.backgroundColor = [UIColor lightGrayColor];
testLabel.textAlignment = NSTextAlignmentCenter;
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"天天撸啊撸啊撸啊撸"];
[AttributedStr addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:16.0]
range:NSMakeRange(2, 2)];
[AttributedStr addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(2, 2)];
testLabel.attributedText = AttributedStr;
[self.view addSubview:testLabel];

6.参考资料

http://blog.csdn.net/reylen/article/details/41208747
http://www.jianshu.com/p/e8e968551ddd

相关文章

网友评论

      本文标题:【iOS】富文本

      本文链接:https://www.haomeiwen.com/subject/ijnxgttx.html