How to have a dynamic List of Views using SwiftUI

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

    if/let flow control statement cannot be used in a @ViewBuilder block.

    Flow control statements inside those special blocks are translated to structs.

    e.g.

    if (someBool) {
        View1()
    } else {
        View2()
    }
    

    is translated to a ConditionalValue.

    Not all flow control statements are available inside those blocks, i.e. switch, but this may change in the future.

    More about this in the function builder evolution proposal.


    In your specific example you can rewrite the code as follows:

    struct ContentView : View {
    
        let elements: [Any] = [View1.self, View2.self]
    
        var body: some View {
            List {
                ForEach(0..

提交回复
热议问题