利用 UILabel 的 attributedText 属性可设置不同的文本样式
- 首先初始化一个NSAttributedString
NSMutableAttributedString *abStr = [[NSMutableAttributedString alloc] initWithString:@"你看我是富文本"];
这里初始加给label.attributedText,看起来是平平无奇的样子
这里要先设置label的初始textColor和font等,展示基本样式

- 然后选择一种样式给label变身吧
这里用到NSAttributedString的各种属性来设置相应的样式
1. 设置字体和大小
NSFontAttributeName

//设置前三个字 [UIFont systemFontOfSize:15]
[abStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, 3)];
2. 设置间距
NSParagraphStyleAttributeName

// 这里要用NSMutableParagraphStyle来设置各种属性
// 下面只是简单常用的处理行间距
// 还可以设置首行缩进,行高,对齐方式,段落,连字属性等
NSMutableParagraphStyle *pgpStyle = [[NSMutableParagraphStyle alloc] init];
pgpStyle.lineSpacing = 30; //行间距,注意:实际视觉行距要计算到实际行高
// 行间距是多少倍
// pgpStyle.lineHeightMultiple = 1.5f;
// 首行缩进
// pgpStyle.firstLineHeadIndent = 30.0f;
// 对齐方式
// pgpStyle.alignment = NSTextAlignmentLeft;
// 内容超出宽度时,内容有...省略的位置 ( "...abc" ,"abc..." ,"ab...c")
// pgpStyle.lineBreakMode = NSLineBreakByTruncatingTail;
// 整体缩进
// pgpStyle.headIndent = 30;//左边距
// pgpStyle.tailIndent = 20;//右边距
// 行高
// 针对不同的字型与字号,可以透过指定最大与最小行距来避免过高或过窄的状况发生
// pgpStyle.minimumLineHeight = 10;//最低行高
// pgpStyle.maximumLineHeight = 20;//最大行高
// 段落
// pgpStyle.paragraphSpacing = 15; //段落间距
// pgpStyle.paragraphSpacingBefore = 30;//段首行空白空间
// pgpStyle.paragraphSpacing = 30; //段落后面的间距
[abStr addAttribute:NSParagraphStyleAttributeName
value:pgpStyle
range:NSMakeRange(0, 5)];
3. 设置文本颜色
NSForegroundColorAttributeName
[abStr addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0, 3)];
4. 设置文字背景色
NSBackgroundColorAttributeName
[abStr addAttribute:NSBackgroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0, 3)];
5. 设置连字
NSLigatureAttributeName
说明:
1.PingFangSC_Bold 和 PingFangSC_Regular 一般不会有连字问题
2.PingFangSC-Semibold等字体或者三方字体就有默认连字现象
3.也不是所有的字都会连,一般出现在fi和fl这种字符才会连,具体"连字"的概念问百度or谷歌
NSMutableAttributedString *abStr = [[NSMutableAttributedString alloc]initWithString:@"fiflfi"];
//0表示不连 1表示连 实际中PingFangSC-Semibold等是默认连的
[abStr addAttribute:NSLigatureAttributeName value:@(1)

本文详细介绍如何使用NSAttributedString和UILabel的attributedText属性实现富文本样式,包括字体、大小、颜色、背景色、间距、连字、描边、阴影、链接等17种样式设置方法。
最低0.47元/天 解锁文章
3414

被折叠的 条评论
为什么被折叠?



