SwiftUI
Attributed String
iOS Development
Swift Programming
User Interface Design

How to use Attributed String in SwiftUI

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Modern SwiftUI has first-class support for rich text through AttributedString. That means many use cases that once required wrapping UILabel or juggling NSAttributedString can now be handled directly in SwiftUI with a clearer, value-type API.

Start with AttributedString

If you target a recent SwiftUI stack, the natural entry point is Foundation’s AttributedString.

swift
1import SwiftUI
2
3struct ContentView: View {
4    var body: some View {
5        var text = AttributedString("Hello SwiftUI")
6        text.foregroundColor = .blue
7        text.font = .title
8
9        return Text(text)
10            .padding()
11    }
12}

Text can render an AttributedString directly. That is the simplest modern path.

Style Only Part of the Text

The main benefit of attributed text is that different ranges can carry different styles.

swift
1import SwiftUI
2
3struct ContentView: View {
4    var body: some View {
5        var message = AttributedString("Important warning")
6
7        if let range = message.range(of: "Important") {
8            message[range].foregroundColor = .red
9            message[range].font = .headline.bold()
10        }
11
12        return Text(message)
13            .padding()
14    }
15}

This is much cleaner than splitting a string into several Text views just to vary one word’s styling.

Build Rich Text from Markdown

AttributedString can also be initialized from Markdown, which is very convenient for content-driven UIs.

swift
1import SwiftUI
2
3struct ContentView: View {
4    var body: some View {
5        let markdown = try? AttributedString(
6            markdown: "This is **bold** and this is _italic_."
7        )
8
9        return Group {
10            if let markdown {
11                Text(markdown)
12            } else {
13                Text("Failed to render text")
14            }
15        }
16        .padding()
17    }
18}

This is especially useful when formatted text comes from configuration, CMS content, or local documentation-like strings.

Bridge from NSAttributedString When Needed

You may still receive NSAttributedString from older APIs or UIKit code. Bridging is possible.

swift
1import SwiftUI
2
3struct ContentView: View {
4    var body: some View {
5        let ns = NSAttributedString(
6            string: "Legacy attributed text",
7            attributes: [.foregroundColor: UIColor.systemGreen]
8        )
9
10        if let swiftAttributed = try? AttributedString(ns, including: \ .uiKit) {
11            return AnyView(Text(swiftAttributed).padding())
12        }
13
14        return AnyView(Text("Fallback").padding())
15    }
16}

This lets you move incrementally from UIKit-style attributed text toward native SwiftUI code.

Attributed text is also useful for semantic values such as links.

swift
1import SwiftUI
2
3struct ContentView: View {
4    var body: some View {
5        var text = AttributedString("Open the docs")
6
7        if let range = text.range(of: "docs") {
8            text[range].link = URL(string: "https://developer.apple.com")
9            text[range].foregroundColor = .blue
10            text[range].underlineStyle = .single
11        }
12
13        return Text(text)
14            .padding()
15    }
16}

SwiftUI can render that as interactive rich text without a custom text view wrapper.

When Text Is Enough and When It Is Not

AttributedString is excellent for inline styling, links, emphasis, and moderate rich-text use cases.

It may still be insufficient when you need:

  • advanced text editing
  • complex text layout behavior
  • full UIKit text-system features not surfaced in SwiftUI

In those cases, wrapping UIKit through UIViewRepresentable may still be appropriate. But for display-only rich text, modern AttributedString covers much more than older SwiftUI versions did.

Keep the Styling Logic Local

A practical pattern is to build a small helper that returns attributed content for one UI concern.

swift
1import SwiftUI
2
3func makeStatusText(isError: Bool) -> AttributedString {
4    var text = AttributedString(isError ? "Status: Error" : "Status: OK")
5
6    if let range = text.range(of: isError ? "Error" : "OK") {
7        text[range].foregroundColor = isError ? .red : .green
8        text[range].font = .headline.bold()
9    }
10
11    return text
12}

That keeps formatting rules explicit and testable instead of burying them in the view body.

Common Pitfalls

The biggest mistake is reaching for NSAttributedString wrappers immediately when AttributedString and Text already solve the display problem.

Another mistake is using many concatenated Text fragments for styling that would be cleaner as one attributed value.

Developers also sometimes forget that not every NSAttributedString attribute maps cleanly into SwiftUI’s native rendering model. Bridging helps, but it does not guarantee full UIKit behavior.

Finally, keep target-platform constraints in mind. If you support older OS versions, verify that the APIs you rely on are available in your deployment target.

Summary

  • In modern SwiftUI, use AttributedString as the primary rich-text API.
  • 'Text can render an AttributedString directly.'
  • Style substrings by finding ranges and assigning attributes to them.
  • Markdown and NSAttributedString bridging are both useful entry points.
  • Use UIKit wrappers only when your text needs exceed what SwiftUI’s native attributed text support provides.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.