在iOS中的文本样式是固定的,只能设置字体样式(font)或者设置字体,如果需要自定义文本样式,则需要用属性文本(NSAttributedString/NSMutableAttributedString)来设置,下面是一些常见的文本属性:
1.NSFontAttributeName:设置字体大小;
2.NSForegroundColorAttributeName:设置字体颜色;
3.NSUnderlineColorAttributeName:设置下划线颜色
4.NSUnderlineStyleAttributeName:设置下划线样式
5.NSBackgroundColorAttributeName:设置背景颜色
6.NSLinkAttributeName:给文字添加连接(适用于UITextView)
7.NSParagraphStyleAttributeName:设置排版样式(包含字间距、行间距等属性)
8.NSLigatureAttributeName:设置连体属性
9.NSKernAttributeName:设置字符间距
10.NSStrikethroughStyleAttributeName:设置删除线
11.NSStrokeColorAttributeName:设置画笔颜色
12.NSStrokeWidthAttributeName:设置画笔宽度
13.NSShadowAttributeName:设置阴影属性
14.NSTextEffectAttributeName:设置文本特殊效果
15.NSAttachmentAttributeName:设置文本附件
16.NSBaselineOffsetAttributeName:设置基线偏移量
17.NSStrikethroughColorAttributeName:设置删除线颜色
18.NSObliquenessAttributeName:设置字体倾斜度
19.NSExpansionAttributeName:设置文本横向拉伸属性
20.NSWritingDirectionAttributeName:设置文本书写方向
21.NSVerticalGlyphFormAttributeName:设置文本排版方向
而有时后会遇到图文混排,或者一些简单的图片+文字的UI也可以用图文混排来实现:
1.在属性文字中插入图片需要用到NSTextAttachment:
NSTextAttachment *attchment = [[NSTextAttachment alloc]init]; //初始化
attchment.bounds=CGRectMake(0, -2.5,12,15);//设置frame
attchment.image= [UIImage imageNamed:@"定位_nor"];//设置需要插入的图片
2.将NSTextAttachment转换成NSAttributedString/NSMutableAttributedString:
NSAttributedString *attchmentString = [NSAttributedString attributedStringWithAttachment:(NSTextAttachment *)(attchment)];
3.将图片插入到相应的位置
[attributedString insertAttributedString:attchmentString atIndex:i];//插入到第I个位置
需要注意的是,NSTextAttachment的位置bounds并不支持异步加载,也就是单图片被插入到attributedString后,再去设置这个属性的时候,就已经失效了,因此加载网络图片的时候需要先下载图片,在插入,下面我们用SDWebImage来完成加载网络图片的过程:
[[SDWebImageManagersharedManager]downloadImageWithURL:url options:0progress:nil completed:^(UIImage *image,NSError *error,SDImageCacheType cacheType,BOOL finished,NSURL *imageURL) {
if(image) {
NSTextAttachment *attchment = [[NSTextAttachment alloc]init]; //初始化
attchment.bounds=CGRectMake(0, -2.5,12,15);//设置frame
attchment.image= image;//设置需要插入的图片
NSAttributedString *attchmentString = [NSAttributedString attributedStringWithAttachment:(NSTextAttachment *)(attchment)];
[attributedString insertAttributedString:attchmentString atIndex:i];//插入到第i个位置
[label setAttributedText:noteStr];
}
}];