SwiftUI:将LazyVGrid单元格扩展到每行的最大高度

afdcj2ne  于 2022-12-10  发布在  Swift
关注(0)|答案(1)|浏览(193)

我在ScrollView中使用LazyVGrid来显示1列(纵向)或2列(横向)布局中的单元格。然而,一行中较短单元格的高度无法扩展到与同一行中较高单元格的高度相匹配,看起来相当糟糕。
我如何确保一行中每个单元格的高度始终相同?显然我不希望每个单元格的高度都是固定的。(需要说明的是,我希望“Church - Eastbound”与“Church & Market”一样高,“West Portal”与“Forest Hill”一样高。

ScrollView(.vertical) {
    LazyVGrid(
        columns: [GridItem(.adaptive(minimum: 400))],
        alignment: .leading,
        spacing: 16
    ) {
        ForEach(sharedFavorites.favoriteStops.indices, id: \.self) { index in
            let favorite = sharedFavorites.favoriteStops[index]
            
            NavigationLink(
                destination: SingleStationView(
                    station: favorite.station,
                    direction: favorite.direction
                )
            ) {
                BoardRow(favorite: favorite, stop: favorite.observableStop)
                    .padding()
                    .background(Color(.secondarySystemGroupedBackground))
                    .cornerRadius(10)
                    .frame(maxHeight: .infinity)
            }
        }
    }
}

截图:

我在BoardRow视图和BoardView的内部内容(这只是一个普通的VStack)上都尝试了.frame(maxHeight: .infinity)。它不起作用。

l2osamch

l2osamch1#

你真的很接近-只需要把.frame(maxHeight:)放在.background之前。

struct ContentView: View {
    var body: some View {
        ScrollView(.vertical) {
            LazyVGrid(
                columns: [GridItem(.adaptive(minimum: 160))],
                alignment: .leading,
                spacing: 16
            ) {
                ForEach([0, 1, 2, 5, 6, 3], id: \.self) { index in

                    BoardCell(index: index)
                        .padding()
                        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
                        .background(Color(.secondarySystemGroupedBackground)) /// `background` goes after the frame!
                        .cornerRadius(10)
                }
            }
            .padding(20)
        }
        .background(Color(.secondaryLabel))
    }
}

/// I recreated your view for testing purposes
struct BoardCell: View {
    var index: Int

    var body: some View {
        VStack(alignment: .leading) {
            Text("Powell (Westbound)")

            ForEach(0 ..< index) { _ in
                HStack {
                    Circle()
                        .fill(.green)
                        .frame(width: 30, height: 30)

                    Text("4")

                    Text("19")

                    Text("17")
                }
            }
        }
    }
}

结果:

相关问题