SwiftUI,索引ViewBuilder的结果

时间:2019-12-10 11:15:26

标签: tuples swiftui builder

我正在尝试实现一种自定义视图,其功能类似于TabView。我正在使用ViewBuilder初始化显示的标签。但是,这意味着当我将多个视图传递给初始化程序时,内容为TupleView。如何一次只显示其中一个视图?

struct TabbedView<Content> : View where Content : View {
    @State var selected:Int = 0
    var content:Content

    var body: some View {
        content
    }

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

struct TestView: View {
    var body: some View {
        TabbedView {
            Text("A")
            Text("B")
        }
    }
}

1 个答案:

答案 0 :(得分:0)

好吧,也许它不是很SwiftUIyish,但它可以工作;)

struct TabbedView<Content> : View where Content : View {
    @State var selected:Int = 0
    var content:[Content]

    var body: some View {
        content[selected]
    }

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

struct ContentView: View {
    var body: some View {
        TabbedView { [
            Text("A"),
            Text("B")
            ]
        }
    }
}