The role of Text view in SwiftUI is to display text (funny that). It can support simple labels, rich content or dynamic text. It is the SwiftUI equivalent to UILabel. Let’s get look at it in more detail.

Creating Basic Text

Simply pass a string to the Text initialiser:

Text("Hello, SwiftUI!")

swiftui text view

You can also use string interpolation to create dynamic text:

let userName = "Mike"
Text("Welcome back, \(userName)!")

swiftui text view username

Text Styling

SwiftUI provides numerous modifiers to style your text. Each modifier returns a new View allowing to chain modifiers to create custom styling.

Font and Weight

Text("Large Title")
    .font(.largeTitle)
    .fontWeight(.bold)

Text("Custom Font")
    .font(.system(size: 18, weight: .medium, design: .rounded))

swiftui text font modifier

The font modifier accepts system fonts like .title, .headline, .body, and .caption, or you can create custom fonts with specific sizes and weights.

Colors and Backgrounds

Text("Colored Text")
    .foregroundColor(.blue)
    .background(Color.yellow)

Text("Gradient Text")
    .foregroundStyle(
        LinearGradient(colors: [.blue, .purple], startPoint: .leading, endPoint: .trailing)
    )

swiftui text background

Text Alignment and Layout

Text("This is a long piece of text that will wrap to multiple lines and demonstrate text alignment.")
    .multilineTextAlignment(.center)
    .lineLimit(3)
    .truncationMode(.tail)

swiftui text alignment

The multilineTextAlignment modifier controls how text aligns when it spans multiple lines, while lineLimit restricts the number of lines displayed.

Formatting Text Content

SwiftUI’s Text view has handy initialisers for styling and formatting specific data types such as dates and currencies.

Dates and Numbers

let currentDate = Date()
let price = 29.99

Text(currentDate, style: .date)
Text(currentDate, style: .time)
Text(currentDate, style: .relative)

Text(price, format: .currency(code: "USD"))

swiftui text dates

SwiftUI automatically formats these types based on the user’s locale and system preferences.

Attributed Text with Markdown

SwiftUI supports basic Markdown formatting directly in text strings:

Text("This text has **bold** and *italic* formatting")
Text("You can also add `inline code` formatting")

swiftui text attributed text

Combining Text Views

Thanks to SwiftUI’s composability, it is easy to combine different Text views with different styling:

Text("Hello, ")
    .font(.body)
    .foregroundColor(.primary) +
Text("World!")
    .font(.title)
    .foregroundColor(.blue)
    .fontWeight(.bold)

swiftui text combining

This creates a single text view with mixed formatting, perfect for creating rich text displays without complex attributed strings.

Dynamic Text with State

Text views naturally work with SwiftUI’s state management system:

struct ContentView: View {
    @State private var counter = 0
    
    var body: some View {
        VStack {
            Text("Count: \(counter)")
                .font(.title)
            
            Button("Increment") {
                counter += 1
            }
        }
    }
}

swiftui text dynamic

Accessibility and Dynamic Type

SwiftUI’s Text view automatically supports Dynamic Type, scaling text based on the user’s accessibility preferences:

Text("This text scales with accessibility settings")
    .font(.body)

For custom fonts, you can ensure they scale properly using relativeTo:

Text("Custom scalable text")
    .font(.custom("Georgia", size: 16, relativeTo: .body))

swiftui text scaling

Text Selection

By default, Text views are not selectable. You can make text selectable by adding the textSelection modifier:

Text("This text can be selected and copied")
    .textSelection(.enabled)

Performance Considerations

Text views are highly optimised in SwiftUI. They automatically handle:

  • Efficient text rendering and layout
  • Dynamic Type scaling
  • Localization and right-to-left text support
  • Memory management for long text content

Common Patterns

Creating Styled Labels

struct StyledLabel: View {
    let title: String
    let value: String
    
    var body: some View {
        HStack {
            Text(title)
                .font(.caption)
                .foregroundColor(.secondary)
            Spacer()
            Text(value)
                .font(.body)
                .fontWeight(.medium)
        }
    }
}

Conditional Text Styling

struct StatusText: View {
    let status: String
    let isError: Bool
    
    var body: some View {
        Text(status)
            .font(.headline)
            .foregroundColor(isError ? .red : .green)
            .padding()
            .background(
                RoundedRectangle(cornerRadius: 8)
                    .fill(isError ? Color.red.opacity(0.1) : Color.green.opacity(0.1))
            )
    }
}

swiftui text conditional

Benefits of SwiftUI Text

  • Declarative Syntax: Text styling is clear and readable, making code easier to maintain.
  • Automatic Adaptation: Built-in support for accessibility, localisation, and device differences.
  • Composable: Easy to combine and style multiple text elements together.
  • Performance: Optimised rendering and memory usage for all text scenarios.

The Text view forms the foundation of most SwiftUI interfaces. It has plenty of modifiers and capabilities. Be sure to give them all a try.

Happy coding.