SwiftUI中的一些视图,如VStack和HStack,支持将多个视图作为子视图,如下所示:
VStack {
Text("hello")
Text("world")
}
据我所知,正如here所解释的那样,他们使用ViewBuilder来实现这一点。
我们如何使用@ViewBuilder来创建我们自己的支持多个子视图的视图?例如,假设我想创建一个接受任意子对象的Layout
视图--如下所示:
struct Layout : View {
let content: Some View
var body : some View {
VStack {
Text("This is a layout")
content()
}
}
}
你知道如何在SwiftUI中实现这个模式吗?
发布于 2019-06-11 04:27:05
下面是一个不做任何事情的示例视图,只是为了演示如何使用@ViewBuilder
。
struct Passthrough<Content>: View where Content: View {
let content: () -> Content
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
var body: some View {
content()
}
}
用法:
Passthrough {
Text("one")
Text("two")
Text("three")
}
https://stackoverflow.com/questions/56532366
复制相似问题