Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a custom container view using @ViewBuilder.
iOS Swift
struct CustomContainer<Content: View>: View {
let content: () -> Content
var body: some View {
VStack {
[1]
}
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the closure name without parentheses, which does not render the content.
Trying to instantiate the Content type instead of calling the closure.
✗ Incorrect
The content closure must be called with parentheses to render the child views inside the VStack.
2fill in blank
mediumComplete the initializer to accept a @ViewBuilder closure for the content.
iOS Swift
struct CustomContainer<Content: View>: View {
let content: () -> Content
init(@ViewBuilder content: @escaping () -> Content) {
self.[1] = content
}
var body: some View {
VStack {
content()
}
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the type name instead of the property name.
Forgetting to use self. to refer to the property.
✗ Incorrect
The initializer assigns the passed closure to the stored property named content.
3fill in blank
hardFix the error in the body by correctly using the @ViewBuilder content closure.
iOS Swift
var body: some View {
HStack {
[1]
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the closure name without parentheses.
Trying to instantiate the Content type.
✗ Incorrect
The content closure must be called with parentheses to produce the views inside the HStack.
4fill in blank
hardFill both blanks to define a custom container that stacks views vertically and accepts multiple child views.
iOS Swift
struct VerticalStack<Content: View>: View {
let content: () -> Content
init(@ViewBuilder content: @escaping () -> Content) {
self.[1] = content
}
var body: some View {
[2] {
content()
}
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using HStack instead of VStack for vertical stacking.
Using the wrong property name in the initializer.
✗ Incorrect
The property content stores the closure, and VStack stacks the child views vertically.
5fill in blank
hardFill all three blanks to create a custom container that arranges child views horizontally with spacing.
iOS Swift
struct HorizontalStack<Content: View>: View {
let content: () -> Content
let spacing: CGFloat
init(spacing: CGFloat = 10, @ViewBuilder content: @escaping () -> Content) {
self.[1] = content
self.[2] = spacing
}
var body: some View {
[3](spacing: spacing) {
content()
}
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up VStack and HStack.
Forgetting to assign spacing in the initializer.
✗ Incorrect
The initializer assigns content and spacing properties, and the body uses HStack with spacing to arrange views horizontally.