DEV Community

RockAndNull
RockAndNull

Posted on • Originally published at paleblueapps.com on

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

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