1、富文本的相关属性字段: NSAttributedString.Key
(1)paragraphStyle
let paraStyle = NSMutableParagraphStyle()
paraStyle.alignment = .center
paraStyle.lineSpacing = 20
paraStyle.lineBreakMode = .byWordWrapping
lineBreakMode
只有当文本内容超出容器大小时才会起作用。
byWordWrapping
: 默认,文本换行以work
为单位byCharWrapping
: 文本换行以char
为单位,当行尾的一个word
放不下时,会按字符分开该word
放到下一行byClipping
: 整体以word
为换行单位,到最后一行仍放不下文本时,会截去多余的部分,可能导致word
被拆分byTruncatingHead/Middle/Tail
: 最后一行还不能装下文本时,开头/中间/结尾用...
表示
(2)baselineOffset
首先了解一下font的各个属性,日常初始化设置的是pointSize
的大小,即字体大小:
baselineOffset
表示font
的lineHeight
和paragraphStyle
的lineHeight
上边界的垂直距离,设置之前一般通过paragraphStyle
的maximumLineHeight
和minimumLineHeight
指定行高。值设为(paraStyle.maximumLineHeight - label.font.lineHeight) / 4
表示居中,至于为什么不除2,官方也没有很明确的解释,可能是由于约束问题。
(3)strokeColor & foregroundColor
二者配合使用可做出下面这种文本效果(需要注意的是strokeWidth
需要为负值,否则不起效果):
let attributes: [NSAttributedString.Key: Any] = [
.strokeWidth: -3,
.strokeColor: UIColor.red,
.foregroundColor: UIColor.yellow
]
2、初始化NSAttributedString
通过string
和attributes
初始化的NSAttributedString
后续无法添加属性,需要用到NSMutableAttributedString
。