Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of custom styles using Markdown support in SwiftUI Text.
import SwiftUI
import PlaygroundSupport
import Foundation
struct MarkdownView: View {
var body: some View {
Text(try! AttributedString(markdown: "This is a **basic** _string_. Italic bits are red. All the **bold** bits are _coloured_ **green**! And [this is a link!](https://q42.nl/).", customBoldColor: .green, customItalicColor: .red))
.font(.title)
}
}
extension AttributedString {
init(markdown: String, customBoldColor: Color, customItalicColor: Color) throws {
try self.init(markdown: markdown)
for run in runs {
// Apply different styles for bold and italic text
switch run.inlinePresentationIntent {
case InlinePresentationIntent.stronglyEmphasized:
self[run.range].foregroundColor = customBoldColor
case InlinePresentationIntent.emphasized:
self[run.range].foregroundColor = customItalicColor
default:
break
}
// Add underline to links
if run.link != nil {
self[run.range].underlineStyle = .single
}
}
}
}
PlaygroundPage.current.setLiveView(MarkdownView())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment