簡體   English   中英

在 SwiftUI 中使用 LazyVGrid 替換背景顏色

[英]Alternate Background Color with LazyVGrid in SwiftUI

有沒有辦法更改 LazyVGrid 中交替行的背景顏色。 我沒有看到這樣做的方法。 我認為一種方法是使用 UITableView,但我想堅持使用 SwiftUI,而不使用 UIKit。

任何指示或方向都會非常有幫助。

謝謝

您可以嘗試以下操作:

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

在此處輸入圖像描述

有用的鏈接:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM