How to have a dynamic List of Views using SwiftUI

后端 未结 8 2017
被撕碎了的回忆
被撕碎了的回忆 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 03:06

    I wanted to use different views in the same list as well and therefore implemented an advanced list view, see here.

    0 讨论(0)
  • 2020-12-05 03:10

    You can do this by polymorphism:

    struct View1: View {
        var body: some View {
            Text("View1")
        }
    }
    
    struct View2: View {
        var body: some View {
            Text("View2")
        }
    }
    
    class ViewBase: Identifiable {
        func showView() -> AnyView {
            AnyView(EmptyView())
        }
    }
    
    class AnyView1: ViewBase {
        override func showView() -> AnyView {
            AnyView(View1())
        }
    }
    
    class AnyView2: ViewBase {
        override func showView() -> AnyView {
            AnyView(View2())
        }
    }
    
    struct ContentView: View {
        let views: [ViewBase] = [
            AnyView1(),
            AnyView2()
        ]
    
        var body: some View {
            List(self.views) { view in
                view.showView()
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题