在 SwiftUI 中使用 LazyVGrid 替换背景颜色

RXP*_*RXP 5 ios swift swiftui

有没有办法更改 LazyVGrid 中交替行的背景颜色。我没有找到办法做到这一点。我认为一种方法是使用 UITableView,但我想坚持使用 SwiftUI,而不使用 UIKit。

任何指示或方向都会非常有帮助。

谢谢

paw*_*222 7

您可以尝试以下操作:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

有用的链接: