Search code examples
swiftuiswiftui-foreach

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


Essentially I would like to alternate the background colors of rows created by the ForEach below, that I will put into a ScrollView in the order of e.g. white, gray, white, gray, etc.

How can this be done?

@State var posts: [Item] = []
@State var expanded = false
@State var totalRows = 0

ForEach(posts.prefix(expanded ? totalRows : 5), id: \.id) { post in
    Label {
        VStack(alignment: .leading) {
            Text(convertDate(post.date))
        }
        .padding(.leading, 8)
    }  icon: {}
}
.frame(width: UIScreen.main.bounds.width - 35, height: 85, alignment: .leading)
.background(Color("cellColor")) //<-- Currently Setting Color Here
.cornerRadius(10)

Solution

  • Try something like this:

     List { // <-- here
        ForEach(Array(posts.prefix(expanded ? totalRows : 5).enumerated()), id: \.0) { index, post in  // <-- here
             VStack {
                 Label {
                     VStack(alignment: .leading) {
                         Text(convertDate(post.date))
                     }
                     .padding(.leading, 8)
                 } icon: {}
             }
             .listRowBackground(index % 2 == 0 ?  Color.gray : Color.white) // <-- here
         }
     }
     .frame(width: 333, height: 444, alignment: .leading) // <-- for testing
     .cornerRadius(10)
    

    If you want to use a ScrollView instead of a List, use .background(index % 2 == 0 ? Color.gray : Color.white) instead of the .listRowBackground(...)

    Note, with minor adjustments you can also use .indices instead of .enumerated().