You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Button标签内内容遵循Grid与GridRow的布局规则?

解决SwiftUI中GridRow嵌套Button后的布局对齐问题

方法一:将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 23:07:07