Skip to main content

Text

Definition​

Text is the fundamental view in SwiftUI for displaying read-only text. It supports rich text formatting, localization, and various styling options.

Basic Syntax​

Text("Hello, World!")

Common Modifiers​

Text("Sample Text")
.font(.title) // Sets font style
.foregroundColor(.blue) // Sets text color
.background(Color.yellow) // Sets background color
.padding() // Adds padding around text
.bold() // Makes text bold
.italic() // Makes text italic
.underline() // Adds underline
.strikethrough() // Adds strikethrough
.textCase(.uppercase) // Changes text case
.lineLimit(3) // Limits number of lines
.truncationMode(.tail) // Sets truncation mode
.multilineTextAlignment(.center) // Sets text alignment
.lineSpacing(5) // Adjusts line spacing
.tracking(2) // Adjusts letter spacing

Font Styles​

// System fonts
Text("Large Title").font(.largeTitle)
Text("Title").font(.title)
Text("Title 2").font(.title2)
Text("Title 3").font(.title3)
Text("Headline").font(.headline)
Text("Subheadline").font(.subheadline)
Text("Body").font(.body)
Text("Callout").font(.callout)
Text("Footnote").font(.footnote)
Text("Caption").font(.caption)
Text("Caption 2").font(.caption2)

// Custom fonts
Text("Custom Font")
.font(.custom("Helvetica", size: 18))

// System font with size and weight
Text("Custom System Font")
.font(.system(size: 20, weight: .semibold, design: .rounded))

Colors and Styling​

// Predefined colors
Text("Red Text").foregroundColor(.red)
Text("Blue Text").foregroundColor(.blue)
Text("Primary Text").foregroundColor(.primary)
Text("Secondary Text").foregroundColor(.secondary)

// Custom colors
Text("Custom Color")
.foregroundColor(Color(red: 0.8, green: 0.2, blue: 0.6))

// Gradient text (iOS 15+)
Text("Gradient Text")
.foregroundStyle(
LinearGradient(
colors: [.red, .blue],
startPoint: .leading,
endPoint: .trailing
)
)
.font(.largeTitle)
.bold()

Text Formatting​

// Combined formatting
Text("Important Message")
.font(.title2)
.bold()
.italic()
.underline(true, color: .red)
.foregroundColor(.primary)

// Text case transformations
Text("lowercase text").textCase(.uppercase)
Text("UPPERCASE TEXT").textCase(.lowercase)

// Kerning and tracking
Text("Spaced Out Text")
.tracking(3)
.font(.headline)

Multi-line Text​

// Line limits
Text("This is a very long text that might wrap to multiple lines depending on the available space")
.lineLimit(2)
.multilineTextAlignment(.center)

// Line spacing
Text("Line 1\nLine 2\nLine 3")
.lineSpacing(10)
.multilineTextAlignment(.leading)

// Truncation modes
Text("This text will be truncated if it's too long")
.lineLimit(1)
.truncationMode(.middle)

Rich Text and Concatenation​

// Concatenating text views
Text("Hello, ")
.foregroundColor(.black) +
Text("World!")
.foregroundColor(.red)
.bold()

// Using Text with different styles
VStack(alignment: .leading) {
Text("Title")
.font(.title)
.bold() +
Text(" - Subtitle")
.font(.subheadline)
.foregroundColor(.secondary)
}

Markdown Support (iOS 15+)​

// Basic markdown
Text("This is **bold** and *italic* text")

// Links
Text("Visit [Apple](https://apple.com) for more info")

// Complex markdown
Text("""
# Heading
This is a **bold** statement with *italic* emphasis.
Visit [SwiftUI](https://developer.apple.com/swiftui/) for documentation.
""")

Localization​

// Localized text
Text("welcome_message") // Looks up key in Localizable.strings

// Text with interpolation
Text("greeting_\(userName)") // Uses localized string with variable

// Localized with comment
Text("login_button", comment: "Button to log in user")

Dynamic Type Support​

// Automatically scales with user's text size preference
Text("Accessible Text")
.font(.body)

// Custom scaling
Text("Custom Scaling")
.font(.custom("MyFont", size: 16, relativeTo: .body))

// Limiting scaling
Text("Limited Scaling")
.font(.body)
.minimumScaleFactor(0.8)
.lineLimit(1)

Text Selection (iOS 15+)​

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

// Selectable in container
VStack {
Text("First line")
Text("Second line")
Text("Third line")
}
.textSelection(.enabled)

Date and Number Formatting​

// Date formatting
Text(Date(), style: .date)
Text(Date(), style: .time)
Text(Date(), style: .relative)

// Number formatting
Text(1234.56, format: .number)
Text(1234.56, format: .currency(code: "USD"))
Text(0.85, format: .percent)

// Custom date formatting
Text(Date(), formatter: {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}())

Advanced Text Effects​

// Shadow effect
Text("Shadow Text")
.font(.largeTitle)
.bold()
.foregroundColor(.white)
.shadow(color: .black, radius: 2, x: 1, y: 1)

// Overlay effect
Text("Outlined Text")
.font(.largeTitle)
.bold()
.foregroundColor(.white)
.overlay(
Text("Outlined Text")
.font(.largeTitle)
.bold()
.foregroundColor(.clear)
.overlay(
Rectangle()
.stroke(Color.black, lineWidth: 2)
.mask(
Text("Outlined Text")
.font(.largeTitle)
.bold()
)
)
)

Text in Different Contexts​

// Label with icon
Label("Settings", systemImage: "gear")

// Text in buttons
Button(action: {}) {
Text("Tap Me")
.font(.headline)
.foregroundColor(.white)
.padding()
.background(Color.blue)
.cornerRadius(8)
}

// Text in navigation
NavigationView {
Text("Content")
.navigationTitle("Page Title")
.navigationBarTitleDisplayMode(.large)
}

Accessibility​

// Accessibility labels
Text("🎉")
.accessibilityLabel("Party celebration")

// Accessibility traits
Text("Important Notice")
.accessibilityAddTraits(.isHeader)

// Custom accessibility
Text("Custom accessibility")
.accessibilityElement(children: .ignore)
.accessibilityLabel("Custom description")
.accessibilityHint("Double tap for more info")

Performance Tips​

// For large amounts of text, consider using lazy loading
LazyVStack {
ForEach(0..<1000, id: \.self) { index in
Text("Item \(index)")
}
}

// Use string interpolation efficiently
Text("User: \(user.name), Score: \(user.score)")

Best Practices​

  1. Use appropriate font styles: Choose fonts that match your app's hierarchy
  2. Consider accessibility: Test with different text sizes and VoiceOver
  3. Localize your text: Always use localized strings for user-facing text
  4. Handle long text gracefully: Use line limits and truncation appropriately
  5. Test on different devices: Ensure text looks good on various screen sizes
  6. Use semantic colors: Prefer .primary, .secondary over fixed colors
  7. Maintain consistency: Use consistent typography throughout your app

Common Use Cases​

  • Headlines and titles
  • Body text and descriptions
  • Labels and captions
  • Error messages and alerts
  • Navigation titles
  • Button labels
  • Status indicators