简体   繁体   English

如何使用可以像List一样填充的主体制作可重复使用的SwiftUI View?

[英]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. 我想制作一个通用的SwiftUI视图,可以将其插入和插入控件。 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这样:

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: 您可以使用@ViewBuilder属性包装器:

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")
        }
    }
}


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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