Rendering Markdown Text with AttributedString in SwiftUI

AttributeContainer, along with AttributedString, allows us to easily style our Texts - wether it's by adding a foreground color, a background color or adding an underline. Any Text style can be easily achieved with AttributeContainer. Let's see how to make use of it!

Style AttributedStrings with AttributeContainer

Disclaimer

AttributeContainer is only supported in applications running on iOS 15.0 and higher. You'll need Xcode 13 and need to set your Xcode project's iOS target version to iOS 15.0 or higher, or wrap the code presented in this section in an if #available(iOS 15.0, *).

Create an AttributedString

First, to use AttributeContainer, we'll need an AttributedString. 

Think of the AttributeContainer as a box, with styling added to the box. Without an AttributedString - or content, the box is useless. So let's create the AttributedString as a computed property.

var attributedString: AttributedString {

}

..

Inside of it, I'll create a simple AttributedString with my name.

var name = AttributedString("SwiftUIio")

..

Create container

Next, initialize an AttributeContainer.

var container = AttributeContainer()

..

Add styling to your AttributeContainer.

container.foregroundColor = .blue
container.underlineStyle = .single
container.underlineColor = .blue

..

We need to merge our container's attributes with our name, so that our name's foreground color is blue, and we'll also see a blue underline.

name.mergeAttributes(container)

..

Return your full string.

return "Hello, " + name

..

Display the new String

Pass the attributedString variable to a Text.

Text(attributedString).bold()

..

And this should be the end result, try in simulator.

..

Comments