How to have a dynamic List of Views using SwiftUI

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

    Looks like the answer was related to wrapping my view inside of AnyView

    struct ContentView : View {
        var myTypes: [Any] = [View1.self, View2.self]
        var body: some View {
            List {
                ForEach(0.. AnyView {
            switch types[index].self {
               case is View1.Type: return AnyView( View1() )
               case is View2.Type: return AnyView( View2() )
               default: return AnyView(EmptyView())
            }
        }
    

    With this, i can now get view-data from a server and compose them. Also, they are only instanced when needed.

提交回复
热议问题