有些关于SwiftUI Builder的帖子,例如this。这样我就可以嵌入我的内容了:
declare global { interface DateAdapterType ... }
我想知道是否不通过init的ViewBuilder。相反,我想做类似的事情:
struct Container<Content>: View where Content: View {
var content: Content
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content()
}
var body: some View {
return content
}
}
struct ContentView: View {
var body: some View {
Container() {
Text("Content 1").tag(0)
Text("Content 2").tag(1)
}
}
}
我要这样做的原因是因为我想模仿 struct ContentView: View {
var body: some View {
Container().buildContent {
Text("Content 1").tag(0)
Text("Content 2").tag(1)
}
}
}
的 TabView
。
答案 0 :(得分:0)
您不能让buildContent
函数对Container
进行突变,但是您可以默认将Container
仅仅出售给EmptyView
,并将其用作用来创建具有所需内容的新Container
的跳板。
您可以实现如下所示的API:
struct Container<Content>: View where Content: View {
var content: Content
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content()
}
var body: some View {
return content
}
}
extension Container where Content == EmptyView {
init() {
self.content = EmptyView()
}
/// Return a new `Container` with the given `Content` builder.
func buildContent<V : View>(@ViewBuilder content: @escaping () -> V) -> Container<V> {
Container<V>(content: content)
}
}
struct ContentView: View {
var body: some View {
Container().buildContent {
Text("Content 1").tag(0)
Text("Content 2").tag(1)
}
}
}