SwiftUI:如何使用ForEach遍历具有各种代码的各种结构?

问题描述 投票:0回答:1

假设,我有三个名为“ 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个回答
0
投票

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

demo

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)}}
© www.soinside.com 2019 - 2024. All rights reserved.