Add underline and strikethrough styles to Text
Since iOS 15 and macOS 12 we can create SwiftUI Text views with AttributedString.
Within the AttributedString
we can assign underlineStyle and strikethroughStyle attributes to particular ranges of string. SwiftUI Text
view then renders these styles appropriately.
We can use Text.LineStyle to customize the pattern and the color of the line.
struct ContentView: View {
var attributedString: AttributedString {
var result = AttributedString("Hello World!")
result.underlineStyle = Text.LineStyle(
pattern: .dash, color: .purple)
return result
}
var body: some View {
Text(attributedString)
}
}
Check out our new book!
Swift Gems
100+ tips to take your Swift code to the next level
Swift Gems
100+ tips to take your Swift code to the next level
- Advanced Swift techniques for experienced developers bypassing basic tutorials
- Curated, actionable tips ready for immediate integration into any Swift project
- Strategies to improve code quality, structure, and performance across all platforms
- Practical Swift insights from years of development, applicable from iOS to server-side Swift