SwiftUI Modifiers & ViewBuilder
Modifiers & ViewBuilder
Compose views by chaining modifiers and extract reusable building blocks with ViewBuilder.
Modifiers
Modifiers return new views with applied changes such as padding, font, and color.
Example
import SwiftUI
struct ModifiersDemo: View {
var body: some View {
Text("Hello")
.font(.title)
.foregroundStyle(.blue)
.padding()
.background(.blue.opacity(0.1))
.cornerRadius(8)
}
}
import SwiftUI
struct ContentView: View {
var body: some View { ModifiersDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}
This example chains several modifiers to style a text view.
ViewBuilder
Use @ViewBuilder to compose multiple child views in a single return position.
Example
import SwiftUI
@ViewBuilder
func InfoRow(_ title: String, _ value: String) -> some View {
HStack { Text(title).bold(); Spacer(); Text(value) }
}
struct ViewBuilderDemo: View {
var body: some View {
VStack(spacing: 8) {
InfoRow("Name", "SwiftUI")
InfoRow("Version", "5+")
}
.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { ViewBuilderDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}
The example above creates a reusable view builder function that returns a horizontal stack of text views.