How to build container view in SwiftUI

Issue #780

To make a container view that accepts child content, we use ViewBuilder

1
2
3
4
5
6
7
8
9
10
11
struct ContainerView<Content: View>: View {
let content: Content

init(@ViewBuilder content: () -> Content) {
self.content = content()
}

var body: some View {
content
}
}

From Swift 5.4, it can synthesize the init, so we can declare resultBuilder for stored property

struct AwesomeContainerView<Content: View>: View {
    @ViewBuilder
    let content: Content

    var body: some View {
        content
    }
}

Updated at 2021-02-24 21:22:49

Comments