append(attributedString, with: ease)
Swift 5
为便于操作 NSMutableAttributedString 添加一个扩展。
支持动态字体、颜色、下划线、删除线、图片,您可以连锁使用 append 调用。使用 AttributesBuilder 类可以轻松为 Attributed String 创建属性集。
使用 Cocoapods 安装
pod 'appendAttributedString'
以下是一个示例
let label = UILabel()
label.numberOfLines = 0
view.backgroundColor = .darkGray
let string = NSMutableAttributedString()
.appendHeadline("Life can rise,\n")
// call chaining
.appendFootnote("it can fall.\n\n")
// color, underline, strike through, superscript and others
.append("But in the end\nit's just carried ", color: .white)
.append("with the wind\n",
color: .yellow,
font: .dynamic(.systemFont(ofSize: 10)),
baselineOffset: 5)
.append("and one day everything you do will simply cease to be…\n\n",
color: .green,
underlineStyle: .double)
.append("Like a child's ", color: .white)
// even images
.append(image: UIImage(named: "balloon")!,
// (the image will not auto-adjust its height)
height: UIFontMetrics.default.scaledValue(for: 20))
.append("\n\n")
// In specal cases use AttributesBuilder class for easier attributes set up
.append("when it's lost,\nit's a tragic affair\n",
with: AttributesBuilder()
.color(.white)
.shadow(offset: CGSize(width: -7, height: 3),
blurRadius: 5, color: .yellow)
.outline(width: -2, color: .red)
.lineSpacing(30)
.align(.center))
.append("- but it is quickly forgotten.", with:
AttributesBuilder()
.strikeThrough(.double, color: .white)
.align(.right))
textView.attributedText = string
1.2 版本中的重大更改
删除
AttributesBuilder().paragraph(style: _)
添加
AttributesBuilder().paragraphStyle(_)
为确保段落样式始终是可变的实例,删除了接受非可变实例的旧方法。
新方法也更容易阅读。