SwiftUI 中的某些 View ,如 VStack 和 HStack 支持将多个 View 作为 subview ,如下所示:
VStack {
Text("hello")
Text("world")
}
据我所知,他们使用 ViewBuilder使这成为可能,如解释的那样here .
我们如何使用@ViewBuilder 来创建我们自己的支持多个 child 的 View ?例如,假设我想创建一个 Layout
View ,它可以接受任意子项——如下所示:
struct Layout : View {
let content: Some View
var body : some View {
VStack {
Text("This is a layout")
content()
}
}
}
知道如何在 SwiftUI 中实现这种模式吗?
最佳答案
这是一个什么都不做的示例 View ,只是为了演示如何使用 @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")
}
关于swift - 使用@ViewBuilder 创建支持多个 child 的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56532366/