ViewBuilder helps you create custom containers that can hold many views easily. It makes your code cleaner and more flexible.
ViewBuilder for custom containers in iOS Swift
@ViewBuilder content: () -> some View
The @ViewBuilder attribute allows you to write multiple views inside a closure without wrapping them in a container manually.
It automatically combines the views into a single view group.
struct MyContainer<Content: View>: View {
let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
VStack {
content
}
}
}MyContainer {
Text("Hello")
Text("World")
}struct Card<Content: View>: View {
let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
content
.padding()
.background(Color.gray.opacity(0.2))
.cornerRadius(10)
}
}This example shows a custom container called MyContainer that uses @ViewBuilder to accept multiple child views. It stacks them vertically with spacing and adds a blue border around them. Inside the container, we put a title, a subtitle, and a button.
import SwiftUI struct MyContainer<Content: View>: View { let content: Content init(@ViewBuilder content: () -> Content) { self.content = content() } var body: some View { VStack(spacing: 10) { content } .padding() .border(Color.blue, width: 2) } } struct ContentView: View { var body: some View { MyContainer { Text("Hello") .font(.title) Text("This is inside a custom container.") .foregroundColor(.gray) Button("Tap me") { print("Button tapped") } .buttonStyle(.borderedProminent) } .padding() } } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
Use @ViewBuilder only on closures that return views.
It helps avoid manually wrapping views in containers like VStack or HStack.
Remember to specify the generic Content: View type when creating custom containers.
ViewBuilder lets you create flexible containers that hold multiple views.
It simplifies writing child views inside closures without extra wrappers.
Custom containers with @ViewBuilder make your UI code cleaner and reusable.