如何让Button标签内内容遵循Grid与GridRow的布局规则?
方法一:将Button作为GridRow的背景层(推荐)
保持GridRow在Grid中的原生布局逻辑,通过给GridRow添加背景按钮实现整行可点击,完全不破坏原有的列对齐:
VStack { Text(table.name) Grid { ForEach(currents) { current in GridRow { Text(current.type) .gridColumnAlignment(.trailing) Text(current.time) .gridColumnAlignment(.center) Text(current.speed) .gridColumnAlignment(.center) } .background( Button(action: { selectedCurrent = current // 执行点击逻辑 }) { Color.clear } .buttonStyle(PlainButtonStyle()) ) } } }
原理:用透明背景的Button填充整个GridRow区域,既保留了Grid的列对齐规则,又实现了整行点击的交互。
方法二:调整Button样式与GridRow尺寸
如果需要将GridRow放在Button内部,需重置Button默认样式并让GridRow占满Button空间:
VStack { Text(table.name) Grid { ForEach(currents) { current in Button(action: { selectedCurrent = current // 执行点击逻辑 }) { GridRow { Text(current.type) .gridColumnAlignment(.trailing) Text(current.time) .gridColumnAlignment(.center) Text(current.speed) .gridColumnAlignment(.center) } .frame(maxWidth: .infinity) } .buttonStyle(PlainButtonStyle()) .gridColumnAlignment(.leading) } } }
原理:通过frame(maxWidth: .infinity)让GridRow填满Button宽度,PlainButtonStyle()移除Button默认的内边距和背景样式,确保Grid布局不受干扰。
内容的提问来源于stack exchange,提问作者Peel
相关产品推荐
相关产品推荐

