0
0
iOS Swiftmobile~10 mins

ViewBuilder for custom containers in iOS Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Acontent
Bcontent()
CContent
DContent()
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.
2fill in blank
medium

Complete 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'
Acontent
BContent
Cbody
Dview
Attempts:
3 left
💡 Hint
Common Mistakes
Using the type name instead of the property name.
Forgetting to use self. to refer to the property.
3fill in blank
hard

Fix 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'
Acontent.self
Bcontent
CContent()
Dcontent()
Attempts:
3 left
💡 Hint
Common Mistakes
Using the closure name without parentheses.
Trying to instantiate the Content type.
4fill in blank
hard

Fill 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'
Acontent
Bbody
CVStack
DHStack
Attempts:
3 left
💡 Hint
Common Mistakes
Using HStack instead of VStack for vertical stacking.
Using the wrong property name in the initializer.
5fill in blank
hard

Fill 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'
Acontent
Bspacing
CHStack
DVStack
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up VStack and HStack.
Forgetting to assign spacing in the initializer.