Forem

RockAndNull
RockAndNull

Posted on • Originally published at paleblueapps.com on

1

How to style a Text in SwiftUI

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.

How to style a Text in SwiftUI

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()
}
Enter fullscreen mode Exit fullscreen mode

And the result:

How to style a Text in SwiftUI

Happy coding!!!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (1)

Collapse
 
0xwdg profile image
Wesley de Groot

Good post.
I would suggest adding some information markdown does not work always out of the box.
especially with dynamic strings.

For dynamic strings you can use:

let myVariable = "Some text. with **Markdown**"
Text(.init(myVariable))
Enter fullscreen mode Exit fullscreen mode

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up