首页 > 解决方案 > SwiftUI - 更新 ForEach 循环中的变量以替换列表的背景颜色

问题描述

我尝试为列表实现一个 pingpong 变量,以便可以交替背景颜色。出于某种原因,以下抛出和错误,但编译器只是说“构建失败”。当我从视图中删除“switchBit”函数调用时,它编译得很好。有人可以帮我理解我在这里做错了什么吗?


struct HomeScreen: View {
    let colors: [Color] = [.green,.white]
    @State var pingPong: Int = 0

    var body: some View {


        NavigationView{
            GeometryReader { geometry in
                ScrollView(.vertical) {
                    VStack {
                        ForEach(jobPostingData){jobposting in

                             NavigationLink(destination: jobPostingPage()) {
                                JobListingsRow(jobposting: jobposting).foregroundColor(Color.black).background(self.colors[self.pingPong])


                            }

                            self.switchBit()
                        }

                    }
                    .frame(width: geometry.size.width)
                }
            }

            .navigationBarTitle(Text("Current Listed Positons"))
        }

    }

    func switchBit() {
        self.pingPong = (self.pingPong == 1) ? 0 : 1
    }

}

标签: swiftuiswiftui-list

解决方案


我猜你想要行的替代花腔。您将不得不避免使用 switchBit 代码并使用类似下面的代码来切换颜色:

struct Homescreen: View {
  let colors: [Color] = [.green,.white]
  @State var jobPostingData: [String] = ["1","2", "3","4"]
  @State var pingPong: Int = 0

  var body: some View {


    NavigationView{
        GeometryReader { geometry in
            ScrollView(.vertical) {
                VStack {
                    ForEach(self.jobPostingData.indices, id: \.self) { index in

                        JobListingsRow(jobposting: self.jobPostingData[index])
                            .foregroundColor(Color.black)
                            .background(index % 2 == 0 ? Color.green : Color.red)

                    }

                }

                .frame(width: geometry.size.width)
            }
        }

        .navigationBarTitle(Text("Current Listed Positons"))
    }

}

}

推荐阅读