swiftuiswiftui-navigationlinkswiftui-foreach

SwiftUI - How to alternate the background color of Views in a VStack created by a ForEach loop?


I tried to implement a "pingpong" variable so I could alternate the background color of Views in a VStack.

For some reason the code below doesn't work and causes the compiler to report "Failed to Build."

When I remove the call to the switchBit() function from within the View, it compiles fine. What I am doing wrong here?

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 Positions"))
        } 
    }
    
    func switchBit() {
        self.pingPong = (self.pingPong == 1) ? 0 : 1
    }
}

Solution

  • I guess you want alternate coloraturas for the rows. You will have to avoid the switchBit code and use something like below to switch colours:

    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"))
        }
    
    }
    
    }