0
0
Ios-swiftHow-ToBeginner ยท 3 min read

How to Use Text in SwiftUI: Simple Guide with Examples

In SwiftUI, use the Text view to display text on the screen by passing a string to it, like Text("Hello World"). You can customize its appearance with modifiers such as .font() and .foregroundColor().
๐Ÿ“

Syntax

The Text view creates a text label in SwiftUI. You start with Text("Your string here"). You can then add modifiers to change how it looks or behaves.

  • Text("string"): Displays the string.
  • .font(): Changes the font style and size.
  • .foregroundColor(): Changes the text color.
swift
Text("Hello, SwiftUI!")
  .font(.title)
  .foregroundColor(.blue)
Output
A blue-colored text label saying "Hello, SwiftUI!" in title font size.
๐Ÿ’ป

Example

This example shows a simple SwiftUI app displaying a styled text label in the center of the screen.

swift
import SwiftUI

struct ContentView: View {
  var body: some View {
    Text("Welcome to SwiftUI")
      .font(.largeTitle)
      .foregroundColor(.green)
      .padding()
      .frame(maxWidth: .infinity, maxHeight: .infinity)
      .background(Color.white)
      .multilineTextAlignment(.center)
  }
}

@main
struct MyApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}
Output
A large green text "Welcome to SwiftUI" centered with padding around it.
โš ๏ธ

Common Pitfalls

Beginners often forget that Text is a view and must be inside a SwiftUI view hierarchy. Another mistake is trying to change text content after creation, which is not possible because Text is immutable. Instead, use state variables to update text dynamically.

swift
/* Wrong: Trying to change Text content directly */
// Text("Hello").text = "Hi" // This is not allowed

/* Right: Use a state variable to update text */
import SwiftUI

struct ContentView: View {
  @State private var message = "Hello"

  var body: some View {
    VStack {
      Text(message)
      Button("Change Text") {
        message = "Hi"
      }
    }
  }
}
Output
Shows "Hello" text and a button; tapping button changes text to "Hi".
๐Ÿ“Š

Quick Reference

ModifierPurposeExample
.font()Change font style and sizeText("Hi").font(.headline)
.foregroundColor()Change text colorText("Hi").foregroundColor(.red)
.bold()Make text boldText("Hi").bold()
.italic()Make text italicText("Hi").italic()
.underline()Underline textText("Hi").underline()
.lineLimit()Limit number of linesText("Long text").lineLimit(2)
โœ…

Key Takeaways

Use Text("string") to display text in SwiftUI.
Customize text appearance with modifiers like .font() and .foregroundColor().
Text views are immutable; use @State variables to update text dynamically.
Always place Text inside a SwiftUI view hierarchy.
Use modifiers to style text simply and clearly.