Categories
SwiftUI

Create Your Own View Container Using @ViewBuilder

@ViewBuilder is a function builder that constructs views from closures. It enables you to construct a View that can hold multiple Views. With @ViewVuilder, you can set up your constant elements across the app and View’s Modifiers, then only add to it the content that is changing.


In the example below, we are defining a container view that takes some contents of type View. You can see that we added modifiers to the content inside the body variable. The modifiers are going to be applied to all the content that you pass to this container.

struct Container <Content : View> : View {
    var content : Content
    
    init(@ViewBuilder content: () -> Content) {
        self.content = content()
    }
    
    var body: some View {
        content
            .padding()
            .background(Color.green)
            .cornerRadius(20)
    }
}

Inside ContentView, we can add our container. You can add the UI elements you need inside this container.

struct ContentView: View {
    var body: some View {
        Container {
            Text("This is my")
            Text("Container's content")
        }
    }
}
@ViewBuilder, build a view, container, Stack View, swiftui, swiftui tutorials
@ViewBuilder container