首页 > 解决方案 > ForEach 具有动态与静态范围

问题描述

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

我有以下简单的演示来显示我的问题。anySquare 上的 tapGesture 将更新 @State 变量数组以使正方形 1 消失/出现。像右侧的魅力一样工作,但不在 ForEach 内。

点击之前/之后

@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()
                                }
                        }
                    }
                }
            }
        }
    }

标签: swiftui

解决方案


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

ForEach(_:content:)应该只用于常量数据。而是使数据符合Identifiable或使用ForEach(_:id:content:) 并提供明确的id!

您可以使用此代码来完成您的ForEach工作:

ForEach(visibilityArray, id: \.self) {

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


推荐阅读