简体   繁体   中英

How do I make a reusable SwiftUI View with a body I can fill in like List?

I want to make a generic SwiftUI View that I can plug in and out of my controls. More than just passing it data though, I want to be able to pass in subviews like you would to a List like so:

List{
    Text("This works")
    Text("Hello World")
    Text("This works")
}

MyClass {
    Text("This works")
    Text("Hello World")
    Text("This works")
}

Is this possible? And if so, how would I go about declaring this class?

You can use the @ViewBuilder property wrapper:

struct CustomView<Content: View>: View {
    var content: () -> Content

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

    var body: some View {
        VStack {
            content()
        }
    }
}


struct ContentView: View {
    var body: some View {
        CustomView {
            Text("hello")
            Text("world")
        }
    }
}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM