DEV Community

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

Sentry mobile image

App store rankings love fast apps - mobile vitals can help you get there

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay