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

SwiftUI Form中HStack嵌套按钮仅最后一个可点击如何解决?

问题解决:HStack中多个Button仅最后一个可点击

问题原因

Form的Section会强制内部视图填充可用空间,但你代码里HStack中的Button没有设置宽度约束,导致所有Button被压缩到最小尺寸并重叠在一起。点击时实际触发的始终是最后一个Button的点击区域。

修复方案

给每个Button添加.frame(maxWidth: .infinity)修饰符,让它们平分HStack的宽度,各自拥有独立的点击区域:

struct ContentView: View {
    @State var selectedOption: String = ""
    var body: some View {
        Form{
            Section {
                HStack(spacing: 1) {
                    Button ("Weight") {
                        selectedOption = "Weight"
                    }
                    .frame(maxWidth: .infinity)
                    .padding()
                    .foregroundColor(.mint)
                    .background(.black)
                    .font(.title3)
                    
                    Button ("Length") {
                        selectedOption = "Length"
                    }
                    .frame(maxWidth: .infinity)
                    .padding()
                    .foregroundColor(.mint)
                    .background(.black)
                    .font(.title3)
                    
                    Button ("Temperature") {
                        selectedOption = "Temperature"
                    }
                    .frame(maxWidth: .infinity)
                    .padding()
                    .foregroundColor(.mint)
                    .background(.black)
                    .font(.title3)
                    
                    Button ("Area") {
                        selectedOption = "Area"
                    }
                    .frame(maxWidth: .infinity)
                    .padding()
                    .foregroundColor(.mint)
                    .background(.black)
                    .font(.title3)
                }
            }
            Section {
                if selectedOption == "Weight" {
                    Weight_View()
                } else {
                    Text(selectedOption)
                }
            }.frame(height: 500)
        }
    }
}

补充说明

.frame(maxWidth: .infinity)会让Button尽可能占据HStack中的可用空间,四个Button会自动平分宽度,这样每个Button的点击区域不再重叠,点击对应按钮就能正确触发事件。

内容的提问来源于stack exchange,提问作者Selva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 18:53:17