如何使用SwiftUI具有动态视图列表 [英] How to have a dynamic List of Views using SwiftUI

查看:279
本文介绍了如何使用SwiftUI具有动态视图列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以做一个静态列表

List {
   View1()
   View2()
}

但是我如何从数组中动态列出元素? 我尝试了以下操作,但出现错误:包含控件流语句的封闭不能与函数生成器'ViewBuilder'一起使用

But how do i make a dynamic list of elements from an array? I tried the following but got error: Closure containing control flow statement cannot be used with function builder 'ViewBuilder'

    let elements: [Any] = [View1.self, View2.self]

    List {
       ForEach(0..<elements.count) { index in
          if let _ = elements[index] as? View1 {
             View1()
          } else {
             View2()
          }
    }
}

对此有任何解决方法吗? 我要完成的工作是一个列表,其中包含不是静态输入的动态元素集.

Is there any work around for this? What I am trying to accomplish is a List contaning dynamic set of elements that are not statically entered.

推荐答案

答案似乎与将我的视图包装在AnyView

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..<myTypes.count) { index in
                self.buildView(types: self.myTypes, index: index)
            }
        }
    }

    func buildView(types: [Any], index: Int) -> 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.

这篇关于如何使用SwiftUI具有动态视图列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆