Freelancing for Pale Blue

Looking for flexible work opportunities that fit your schedule?


How to style a Text in SwiftUI

iOS Apr 5, 2024

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.

Styling a text with UIKit was like

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!!!

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.