SwiftUI:如何让LazyVGrid每行单元格适配行内最高高度
问题:LazyVGrid 单元格行高不一致的解决办法
问题描述
我在ScrollView中使用LazyVGrid,实现竖屏1列、横屏2列的布局,但同一行中较矮的单元格无法自动扩展至该行最高单元格的高度,显示效果差。希望每行所有单元格高度一致(例如“Church - Eastbound”与“Church & Market”等高,“West Portal”与“Forest Hill”等高),且不想使用固定高度。已尝试在BoardRow视图及其内部VStack内容上添加.frame(maxHeight: .infinity),但无效果。
截图说明:2列网格中,每行单元格垂直居中,较矮单元格上下存在空白区域。
原代码
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) } } } }
解决方案
核心问题是NavigationLink未填充父容器高度,需要让链接容器和内部的BoardRow都拉伸至行高。
修改步骤
- 给
NavigationLink添加.frame(maxHeight: .infinity),让链接占满网格单元格的高度 - 确保
BoardRow的根容器(如VStack)添加.frame(maxHeight: .infinity),让内部内容填充可用空间 - 可选:给
GridItem设置alignment: .top,让内容从顶部布局,避免默认垂直居中的视觉空白
调整后的代码
ScrollView(.vertical) { LazyVGrid( columns: [GridItem(.adaptive(minimum: 400), alignment: .top)], 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) } .frame(maxHeight: .infinity) } } }
内容的提问来源于stack exchange,提问作者Naren Hazareesingh
相关产品推荐
相关产品推荐

