【问题标题】:SwiftUI: How to loop through the various structs with various codes, using ForEach?SwiftUI:如何使用 ForEach 循环使用各种代码的各种结构?
【发布时间】:2020-05-16 09:39:28
【问题描述】:

假设,我有三个名为“s001”、“s002”、“s003”的结构。是否可以使用 ForEach 循环来迭代这些结构,而不将它们附加到数组中?

在示例代码下方,仅循环一个结构 (s001)。是否可以使用“s00+(index)”之类的动态结构名称?

import SwiftUI

struct ContentView: View {


var body: some View {
    ForEach((1...3), id: \.self) {index in
               AnyView(s001())

    }

  }
}

struct s001: View {var body: some View {Rectangle().foregroundColor(.red)}}
struct s002: View {var body: some View {Circle().foregroundColor(.blue)}}
struct s003: View {var body: some View {Ellipse().foregroundColor(.yellow)}}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
     }
}

【问题讨论】:

    标签: struct dynamic foreach view swiftui


    【解决方案1】:

    使用AnyView 是可能的,但存在性能缺陷,因此对于所描述的场景,由于这样的结构不应该太多,适当的方法是使用类似 view-factory-builder 的函数,如下所示

    struct S00ContentView: View {
    
        var body: some View {
            ForEach((1...3), id: \.self) {index in
                self.buildView(for: index)
            }
        }
    
        func buildView(for id: Int) -> some View {
            Group {
                if id == 1 {
                    s001()
                }
                else if id == 2 {
                    s002()
                }
                else if id == 3 {
                    s003()
                }
            }
        }
    }
    
    struct s001: View {var body: some View {Rectangle().foregroundColor(.red)}}
    struct s002: View {var body: some View {Circle().foregroundColor(.blue)}}
    struct s003: View {var body: some View {Ellipse().foregroundColor(.yellow)}}
    

    【讨论】:

    • 非常感谢,Asperi,但我想在我的应用程序中拥有多达 20 个不同的结构。所以这将是一段非常长的代码......
    • 好的,接受。 :))) 我只是在寻找更优雅的解决方案......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多