Alternate Background Color with LazyVGrid in SwiftUI

Viewed 1697

Is there a way to change the background color of alternate rows in a LazyVGrid. I did not see a way to do this. I think one way is to use the UITableView but I would like to stick to SwiftUI without using the UIKit.

Any pointers or direction will be very helpful.

Thanks

1 Answers

You can try the following:

struct ContentView: View {
    let columns: Int = 5

    var body: some View {
        let gridItems = Array(repeating: GridItem(.flexible(), spacing: 0), count: columns)
        ScrollView(.vertical) {
            LazyVGrid(columns: gridItems, spacing: 0) {
                ForEach(0 ..< 20) { index in
                    Text("Item \(index)")
                        .padding(10)
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                        .background(isEvenRow(index) ? Color.red: Color.green)
                }
            }
        }
    }

    func isEvenRow(_ index: Int) -> Bool {
        index / columns % 2 == 0
    }
}

enter image description here

Useful links:

Related