在 Swift (iOS/macOS) 中处理 Markdown:库与实践示例
Markdown 是一种轻量级标记语言,广泛用于文档、聊天和教育应用程序中的文本格式化。在 Swift (iOS/macOS) 生态系统中,有多个成熟的库允许将 Markdown 解析、渲染并转换为原生视图。在本文中,我们将介绍主要工具:Down、Ink 和 SwiftMarkdown,并展示在 SwiftUI 和 UIKit 中的集成示例。
1. Down 库 (基于 cmark)
Down 是 Swift 中最流行的 Markdown 处理库。它基于高性能的 C 解析器 cmark,并支持 CommonMark 标准。Down 允许将 Markdown 转换为 HTML、NSAttributedString、PDF,甚至 AST(抽象语法树)。
安装
在 Package.swift 中添加:
dependencies: [ .package(url: "https://github.com/johnxnguyen/Down.git", from: "0.9.4")]示例:将 Markdown 渲染为 NSAttributedString
import Down
let markdownString = "# 标题
这是**粗体**文本和*斜体*。"let down = Down(markdownString: markdownString)
do { let attributedString = try down.toAttributedString() // 在 UITextView 或 UILabel 中使用 textView.attributedText = attributedString} catch { print("解析错误: \\(error)")}Down 还通过 DownStyler 支持自定义样式:
let styler = DownStyler(configuration: DownStylerConfiguration( fonts: FontCollection( heading1: .boldSystemFont(ofSize: 24), body: .systemFont(ofSize: 16) ), colors: ColorCollection( heading1: .systemBlue, body: .label )))let attributedString = try down.toAttributedString(styler: styler)2. Ink 库 (John Sundell)
Ink 是作者 John Sundell 开发的一个轻量级 Markdown 解析器。它不需要外部依赖(纯 Swift),非常适合简单的任务:提取标题、列表、链接。Ink 返回一个块级元素树,可以自定义。
通过 Swift Package Manager 安装
dependencies: [ .package(url: "https://github.com/JohnSundell/Ink.git", from: "0.6.0")]示例:解析并提取标题
import Ink
let markdown = """# 主标题## 副标题带有**粗体**强调的普通文本。"""
let parser = MarkdownParser()let result = parser.parse(markdown)
for heading in result.headings { print("级别 \\(heading.level): \\(heading.text)")}// 输出:// 级别 1: 主标题// 级别 2: 副标题Ink 还支持用于扩展语法的自定义修饰符:
let modifier = Modifier(target: .inlineCode) { html, markdown in return "<span style=\\"color: red;\\">\\(html)</span>"}let parser = MarkdownParser(modifiers: [modifier])3. SwiftMarkdown (来自 Apple)
SwiftMarkdown 是 Apple 在 WWDC 2022 上推出的官方库。它与 SwiftUI 生态系统深度集成,并支持所有 Markdown 扩展,包括表格、带高亮的代码块和嵌套列表。SwiftMarkdown 使用 Foundation 中的 AttributedString,简化了本地化和动态字体。
安装
通过 Xcode 添加到项目:File → Add Packages → apple/swift-markdown。
示例:在 SwiftUI 中显示 Markdown
import MarkdownUIimport SwiftUI
struct ContentView: View { let markdown = """ # 欢迎 这是一个**示例**使用