Skip to content

Instantly share code, notes, and snippets.

@mbernson
Created August 2, 2022 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbernson/ae0b9af2d860746763d0703126c58a8e to your computer and use it in GitHub Desktop.
Save mbernson/ae0b9af2d860746763d0703126c58a8e to your computer and use it in GitHub Desktop.
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