cocoatoucher/StyledMarkdown
Generate SwiftUI Text or AttributedString from markdown strings with custom style names.
Examples
<p align="center"> <img src="Docs/examples.png" width="400" max-width="80%" alt="glide devices"/> </p>
Sample usage
let normalStyle = Style { style in
style.font = .subheadline
style.foregroundColor = .red
}
let boldStyle = Style { style in
style.font = Font.italic(.system(size: 20))()
style.foregroundColor = .blue
}
let myStyleGroup = StyleGroup(
base: normalStyle,
[
"bold": boldStyle
]
)
Text(
"Hey ^[buddy](style: 'bold')",
styleGroup: myStyleGroup
)
// or
AttributedString(
localized: "Hey ^[buddy](style: 'bold')",
styleGroup: myStyleGroup
)The idea of StyleGroup and named Styles comes directly from SwiftRichString library by Daniele Margutti on GitHub. Some of the code from there is also used in this package.
Supported modifiers
font(SwiftUI.Font or UIFont)
foregroundColor(SwiftUI.Color or UIColor)
backgroundColor(SwiftUI.Color or UIColor)
strikethrough(SwiftUI.Color or UIColor)
strikethroughStyle(NSUnderlineStyle)
underline(SwiftUI.Color or UIColor)
underlineStyle(NSUnderlineStyle)
kerning(CGFloat)
tracking(CGFloat)
baselineOffset(CGFloat)
Advanced styling
let rainbow: [Color] = [
.blue, .teal, .red, .gray, .yellow, .orange, .purple
]
let rainbowStyleGroup = StyleGroup(
styleCustom: { source in
var attrString = source
for run in attrString.runs {
let currentRange = run.range
var index = currentRange.lowerBound
var colorCounter: Int = 0
while index < currentRange.upperBound {
let nextIndex = attrString.characters.index(
index,
offsetBy: 1
)
attrString[index ..< nextIndex].foregroundColor = rainbow[colorCounter]
colorCounter += 1
if colorCounter >= rainbow.count {
colorCounter = 0
}
index = nextIndex
}
}
return attrString
}
)
Text(
"Rainbow",
styleGroup: rainbowStyleGroup
)
// or
AttributedString(
localized: "Rainbow",
styleGroup: rainbowStyleGroup
)Parts of the above code for rainbow styling is taken from WWDC'21 sample app project called Caffe, Copyright © 2021 Apple Inc.
🔗 Links
You can add links inside your strings using the custom link AttributedStringKey: ^styled link
iOS Automatic grammar agreement
Automatic grammar agreement's inflect property works with StyledMarkdown styles.
generates 2 salads with italic style.
🎆 Images (not supported)
iOS currently does not support including custom Image attachments within AttributedString.
Package Metadata
Repository: cocoatoucher/StyledMarkdown
Stars: 21
Forks: 3
Open issues: 0
Default branch: main
Primary language: swift
License: MIT
Topics: attributed, attributedstring, ios, localisation, localization, macos, markdown, string, style, styled, swift, swiftui, text, tvos, watchos
README: README.md