How to have a dynamic List of Views using SwiftUI

后端 未结 8 2021
被撕碎了的回忆
被撕碎了的回忆 2020-12-05 02:44

I can do a static List like

List {
   View1()
   View2()
}

But how do i make a dynamic list of elements from an array? I tried the followin

8条回答
  •  [愿得一人]
    2020-12-05 02:46

    SwiftUI 2

    You can now use control flow statements directly in @ViewBuilder blocks, which means the following code is perfectly valid:

    struct ContentView: View {
        let elements: [Any] = [View1.self, View2.self]
    
        var body: some View {
            List {
                ForEach(0 ..< elements.count) { index in
                    if let _ = elements[index] as? View1 {
                        View1()
                    } else {
                        View2()
                    }
                }
            }
        }
    }
    

    SwiftUI 1

    In addition to FlowUI.SimpleUITesting.com's answer you can use @ViewBuilder and avoid AnyView completely:

    @ViewBuilder
    func buildView(types: [Any], index: Int) -> some View {
        switch types[index].self {
        case is View1.Type: View1()
        case is View2.Type: View2()
        default: EmptyView()
        }
    }
    

提交回复
热议问题