NSAttributedString
本文节选自官方文档
NSAttributedString UIKit Additions Reference
属性字顾名思义 就是带有属性的NSString
可以为整个字符串添加各种效果 或者某一部分添加
NSAttributedString和子类NSMutableAttributedString的最大的区别就在于:
NSAttributedString一旦完成初始化创建就不能在后续中更改各种属性或者添加
这点有点类似于NSString和NSMutableString
要想了解属性字 就必须了解其能够设置的各种属性
1. NSUnderlineStyleAttributeName:为文本设置下划线
并且和 NSStrikethroughStyleAttributeName (中划线) 共享样式值
三种基本样式
NSUnderlinePatternDot 该样式单独设置并不能看不出效果 必须配合其他效果组合使用
同理NSUnderlinePatternDash
NSUnderlinePatternDashDot
NSUnderlinePatternDashDotDot
NSUnderlineByWord
以上各样式均是在Range(3,5)的情况下的测试 不是整串都设置了改属性
2.NSFontAttributeName:字体
3.NSParagraphStyleAttributeName:段落样式
4.NSForegroundColorAttributeName:字体颜色
5.NSBackgroundColorAttributeName:背景颜色
6.NSKernAttributeName:字间距 默认值0 浮点数
7.NSStrokeColorAttributeName:设置文字描边颜色,需要和NSStrokeWidthAttributeName:设置描边宽度,这样就能使文字空心.
8.NSShadowAttributeName 设置阴影,单独设置不好使,必须和其他属性搭配才好使。
和这三个任一个都好使,NSVerticalGlyphFormAttributeName,NSObliquenessAttributeName,NSExpansionAttributeName
9.NSVerticalGlyphFormAttributeName
该属性所对应的值是一个 NSNumber 对象(整数)。0 表示横排文本。1 表示竖排文本。在 iOS 中,总是使用横排文本,0 以外的值都未定义
10.NSObliquenessAttributeName:设置字体倾斜。
11. NSExpansionAttributeName:设置文本扁平化
12.NSTextEffectAttributeName:文本特效 就是duang
13.NSAttachmentAttributeName:文本附件,取值为NSTextAttachment对象,常用于文字图片混排
14.NSLinkAttributeName:URL链接
15. NSBaselineOffsetAttributeName:设置基线偏移值,取值为 NSNumber (float),正值上偏,负值下偏
16.NSUnderlineColorAttributeName:下划线颜色
17.NSStrikethroughColorAttributeName:中划线颜色
18.NSWritingDirectionAttributeName:字体书写方向
17. NSDocumentTypeDocumentAttribute:文本属性 描述文本是什么类型的 可是是普通文本 富文本 富文本图文混排文本 超文本标记语言文本
我实在是编不下去了。。。。
下面说说怎么用这个属性字或者说怎么设置
可以在初始的时候就设置好属性
- (instancetype)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;
也可以后期设置
给某个范围的文字添加属性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
设置属性 设置和添加不同 设置会使之前效果消失
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
简单示例
self.view.backgroundColor = [UIColor whiteColor];
CGPoint center = self.view.center;
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
label1.center = CGPointMake(center.x, center.y-100);
NSMutableAttributedString *str1 = [[NSMutableAttributedString alloc] initWithString:@"Helllo World"];
NSDictionary *dic = @{NSBackgroundColorAttributeName:[UIColor grayColor], //背景颜色
NSWritingDirectionAttributeName:@[@(NSWritingDirectionRightToLeft)], //文本书写方向
NSKernAttributeName:@2.5, //文字间隔
NSFontAttributeName:[UIFont systemFontOfSize:24], //字体大小24
NSStrokeColorAttributeName:[UIColor greenColor], //描边颜色
NSStrokeWidthAttributeName:@2, //描边宽度
};
[str1 addAttributes:dic range:NSMakeRange(2, 5)];
[label1 setAttributedText:str1];
[self.view addSubview:label1];
结果如下图
that's all
thx
Everything you see on Screen is UIView.