SwiftUI Form中HStack嵌套按钮仅最后一个可点击如何解决?
问题原因
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
相关产品推荐
相关产品推荐

