Example of custom styles using Markdown support in SwiftUI Text.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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