AttributedStringBuilder:用函数式构建器创建富文本
利用Swift AttributedString的Markdown初始化和自定义AttributeContainer,配合构造函数式构建器(Builder)进行声明式富文本排版。 · 难度:入门 · +10XP
AttributedStringBuilder:用函数式构建器创建富文本
iOS 15+的AttributedString支持Markdown与自定义属性。本教程将教你如何创建一个单一的@AttributedStringBuilder,将多个格式化片段(如加粗、斜体、链接、内联图像)组合起来,并支持嵌套和作用域语法。最后你会得到一个简易的三方排版库核心逻辑,100% Swift原生。
@resultBuilder
struct AttributedStringBuilder {
static func buildBlock(_ components: AttributedString...) -> AttributedString {
components.reduce(into: AttributedString()) { $0.append($1) }
}
}
func attributed(@AttributedStringBuilder content: () -> AttributedString) -> AttributedString {
content()
}
let result = attributed {
AttributedString("Hello ", attributes: [.font: UIFont.boldSystemFont(ofSize: 18)])
AttributedString("World", attributes: [.foregroundColor: UIColor.blue])
}
print(result)