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
| Modifier | Purpose | Example |
|---|---|---|
| .font() | Change font style and size | Text("Hi").font(.headline) |
| .foregroundColor() | Change text color | Text("Hi").foregroundColor(.red) |
| .bold() | Make text bold | Text("Hi").bold() |
| .italic() | Make text italic | Text("Hi").italic() |
| .underline() | Underline text | Text("Hi").underline() |
| .lineLimit() | Limit number of lines | Text("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.