MarkdownWebView
is a surprisingly performant SwiftUI view that renders Markdown content.
I call it surprising because the underlying view is a WKWebView
, yet a SwiftUI scroll view containing a bunch of MarkdownWebView
still scrolls smoothly. A similar looking view built with native SwiftUI views doesn't have such performance (yet, hopefully).
v3.mp4
Dynamic Content
v3.mp4
Syntax Highlighting
Code syntax is automatically highlighted.- macOS 11 and later
- iOS 14 and later
Add this package as a dependency.
See the article “Adding package dependencies to your app” to learn more.
import SwiftUI
import MarkdownWebView
struct ContentView: View {
@State private var markdownContent = "# Hello World"
var body: some View {
NavigationStack {
MarkdownWebView(markdownContent)
}
}
}
The view comes with a default style (CSS files) that suits many use cases.
You can also supply your own stylesheet by setting the customStylesheet
parameter in the initializer.
import SwiftUI
import MarkdownWebView
struct ContentView: View {
@State private var markdownContent = "# Hello World"
private let stylesheet: String? = try? .init(contentsOf: Bundle.main.url(forResource: "markdown", withExtension: "css")!)
var body: some View {
NavigationStack {
MarkdownWebView(markdownContent, customStylesheet: stylesheet)
}
}
}
The view opens links with the default browser by default.
You can handle link activations yourself by setting the onLinkActivation
parameter in the initializer.
import SwiftUI
import MarkdownWebView
struct ContentView: View {
@State private var markdownContent = "# Hello apple.com"
var body: some View {
NavigationStack {
MarkdownWebView(markdownContent)
.onLinkActivation { url in
print(url)
}
}
}
}
The underlying web view loads an HTML string. For the package to work in a macOS app, enable the “Outgoing Connections (Client)” capability.
Portions of this package may utilize the following copyrighted material, the use of which is hereby acknowledged.
- markdown-it
© 2014 Vitaly Puzrin, Alex Kocharin - Punycode.js
© Mathias Bynens - highlight.js
© 2006 Ivan Sagalaev - markdown-it-mark
© 2014-2015 Vitaly Puzrin, Alex Kocharin - markdown-it-task-lists
© 2016, Revin Guillen - github-markdown-css
© Sindre Sorhus