Home > OS >  How does the VStack gets the View elements inside the closure?
How does the VStack gets the View elements inside the closure?

Time:03-16

I'm pretty new to swift and swiftUi, and I wonder how does the VStack (or Hstack, ZStack, etc...) captures the View elements inside the closure?

For example, how does the VStack knows and gets the two Text elements even tho the closure doesn't return anything?

       VStack {
            Text("Hello, world!")
                .padding()
            Text("Hello, world!")
                .padding()
        }

Also, I wander if I can mimic this behavior and implement a struct that does the same?

CodePudding user response:

The closure passed to VStack is a special kind of closure marked with @ViewBuilder

A ViewBuilder is a custom parameter attribute that constructs View from closures. You can create your own ViewBuilders as shown in the example of the ViewBuilder documentation.

  • Related