How to style a Text in SwiftUI
Back when I was still working with UIKit, I'd often find myself wincing at the thought of styling text within the same UILabel. Can you blame me?
NSAttributedString
had a lot of boilerplate code for what should've been a simple task – styling a text. And every time I needed it, I had to search for how to use it because I couldn't remember all that boilerplate code.
Thankfully SwiftUI Text
can now render MarkDown content and can be styled fairly easily.
Below are some examples that are pretty straightforward:
import Foundation
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(spacing: 16) {
Text("This is **bold**")
Text("This is *italic*")
Text("This is ***bold italic***")
Text("This is ~~strikethrough~~")
Text("This is a [link](https://www.paleblueapps.com)")
Text(
"""
\(Text("This is blue").foregroundColor(.blue))\
and\
\(Text("this is yellow").foregroundColor(.yellow))
"""
)
}
}
}
#Preview {
ContentView()
}
And the result:
Happy coding!!!