Search code examples
swiftswiftuixcode11ios13

How can I add a custom container view in SwiftUI


I'm curious if you can create a custom container view within SwiftUI. I know that you can create custom content views, such as Text(), but wasn't sure if you could replicate the functionality of say HStack { }

Something akin to:

HGrid {
    Text("Lorem ipsum")
    Text("Lorem ipsum")
}

Where the custom container view (aka HGrid) would then, say, add Spacer() between each added component. Essentially, as an example, transpiling it to:

HStack {
    Text("Lorem ipsum")
    Spacer()
    Text("Lorem ipsum")
}

Solution

  • SwiftUI implements this with the ViewBuilder @functionBuilder

    struct HGrid <Content: View>: View {
        init(@ViewBuilder builder: () -> Content) {
            let content = builder()
            ...
        }
    }
    

    See also