SwiftUIMidMCQ
What is `ViewBuilder` and how does it work?
Test your knowledge:
Explanation & Code
Answer:
@ViewBuilder is a result builder that lets you write multiple views inside a closure and have them composed into a single view. It's what enables the DSL syntax inside body, VStack, HStack, etc.
Code Example:
// SwiftUI uses @ViewBuilder implicitly in most view builders
struct MyCard<Content: View>: View {
let title: String
@ViewBuilder let content: () -> Content
var body: some View {
VStack(alignment: .leading) {
Text(title).font(.headline)
content() // can be any number of views
}
.padding()
}
}
// Usage
MyCard(title: "Summary") {
Text("Line one")
Text("Line two")
Image(systemName: "star")
}
Rate your understanding: