⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

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)

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 177 篇
0 完成
🔥 0