具有动态范围和静态范围的ForEach

时间:2020-06-04 14:24:33

标签: swiftui

我一直在努力解决另外一个很简单的问题。我似乎找不到在动态范围内使用ForEach的正确方法。

我有以下简单演示演示了我的问题。 anySquare上的tapGesture将更新@State变量数组,以使方格1消失/出现。就像右侧的护身符一样工作,但不在ForEach中。

before / after tap

@State var visibilityArray = [true,true]

    var body: some View {
        ZStack {

            Color.white

            HStack {
                VStack{
                    Text("Dynamic")
                    ForEach(visibilityArray.indices) { i in

                        if self.visibilityArray[i] {
                            Rectangle()
                                .frame(width: 100, height: 100)
                                .overlay(Text(String(i)).foregroundColor(Color.white))
                                .onTapGesture {
                                    withAnimation(Animation.spring()) {
                                        self.visibilityArray[1].toggle()
                                    }
                            }
                        }
                    }
                }

                VStack{
                    Text("Static")
                    if self.visibilityArray[0] {
                        Rectangle()
                            .frame(width: 100, height: 100)
                            .overlay(Text("0").foregroundColor(Color.white))
                            .onTapGesture {
                                withAnimation(Animation.spring()) {
                                    self.visibilityArray[1].toggle()
                                }
                        }
                    }

                    if self.visibilityArray[1] {
                        Rectangle()
                            .frame(width: 100, height: 100)
                            .overlay(Text("1").foregroundColor(Color.white))
                            .onTapGesture {
                                withAnimation(Animation.spring()) {
                                    self.visibilityArray[1].toggle()
                                }
                        }
                    }
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

当您尝试修改在ForEach循环中使用的数组(例如通过将其替换为另一个数组)时发生的Xcode错误提供了很好的指导:

ForEach(_:content:)仅应用于恒定数据。 而是使数据符合Identifiable或使用ForEach(_:id:content:) 并提供明确的id

您可以使用以下代码来使您的ForEach工作:

ForEach(visibilityArray, id: \.self) {

这也意味着对于循环中的每个项目,您都必须返回一些View。我建议将过滤后的数组(仅包含要显示/使用的项)作为输入传递到ForEach循环中。