Markdownosaur 🦖

Markdownosaur 使用 Apple 出色的且相对较新的 Swift Markdown 库来分析 Markdown 源代码,然后将分析结果转换为 NSAttributedString,以便在 iOS、iPadOS 或 Mac 上显示。 它只有几百行代码,并使用了 Apple 库的访问者模式,所以希望它很容易理解。 :)

优势

iOS 15 已经 添加了一个新的初始化器NSAttributedString,它可以处理 Markdown,你应该先检查一下它是否能满足你的需求! 除此之外,Markdownosaur 提供

安装

使用 Swift Package Manager,将 Apple 的 Swift Markdown 库 添加到你的项目。 然后只需获取 Markdownosaur.swift 文件并将其添加到你的项目即可。

(请注意,该库更多是为了提供帮助和指导,并且是从我的使用方式中快速概括出来的,你可能需要修改它以适应你自己的特定样式!)

示例结果

这是设置在 UILabel 上的结果 NSAttributedString(以及可见的 Markdown 源代码)。

An iPhone simulator on the right displaying the result of rendering this repository's test.md file into a UILabel

用法

只需传入 Markdown 源代码,然后将 attributed string 用于任何你想要的地方。

let source = "Here is some **very** cool and simple Markdown"
let document = Document(parsing: source)

var markdownosaur = Markdownosaur()
let attributedString = markdownosaur.attributedString(from: document)

// For instance…
label.attributedText = attributedString

性能

它很快! 比 iOS 15 中的 NSAttributedString 实现略快(Apple 的实现可能更强大)。 以 iPhone 6S Plus(仍然支持 iOS 15 的最旧设备)为例,我使用了 test.md(包含在其中,只是上面“示例结果”的源代码重复了 8 次),平均耗时约 0.04 秒。 与此同时,使用 HTML -> NSAttributedString 转换通过 DTCoreText 处理相同文档平均耗时约 0.1 秒(这是我在使用此工具之前的另一个优秀工具,它可以处理更广泛的 HTML 转换)。

感谢

感谢 Apple 提供了出色的 Swift Markdown 库,并感谢 Down 库的存在,它帮助我弄清楚如何处理某些方面。 还要感谢 @icanzilb@QuietMisdreavus 回答问题!