Attributed String in SwiftUI

Attributed String in SwiftUI

Use NSMutableAttributedString to Create a TextView with multiple styles

·

2 min read

In today’s post, I’d like to share a tip: how to create one Text View with components in different styles. In short, we can use an NSMutableAttributedString as the text value, and prepare the text components with different attributes when the view initiates or updates.

The code in this post is available here.

The code below is the default content view of a SwiftUI file.

struct ContentView: View {
    var body: some View {
        Text("Hello, world")
    }
}

Let’s add an NSMutableAttributedString property in the View and use it in the Text View with String interpolation "\(varName)" .

struct ContentView: View {
    var attributedString = NSMutableAttributedString()
    var body: some View {
        Text("\(attributedString)")
    }
}

Then we can explicitly define an init to prepare the attributed string.

struct ContentView: View {
    var attributedString = NSMutableAttributedString()
    init() {}
    var body: some View {
        Text("\(attributedString)")
    }
}

Inside the init, we can define two NSAttributedString variables as the text component with different fonts and foreground colors.

struct ContentView: View {
    var attributedString = NSMutableAttributedString()
    init() {
        let hello = NSAttributedString(string: "Hello, ", attributes: [.font: UIFont.boldSystemFont(ofSize: 20)])
        let world = NSAttributedString(string: "World!", attributes: [.font: UIFont.systemFont(ofSize: 18), .foregroundColor: UIColor(red: 1, green: 0, blue: 0, alpha: 1)])
    }
    var body: some View {
        Text("\(attributedString)")
    }
}

And finally, we need to append the component hello and world to the NSMutableAttributeString property in the view. So add the lines below at the end of the initializer.

        attributedString.append(hello)
        attributedString.append(world)

And that’s it! You can see the text view populated in the preview canvas with two different styles.