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

SwiftUI中List内HStack嵌套按钮触发异常问题排查

SwiftUI List中行内双按钮点击同时触发的问题解决

问题现象

在SwiftUI的List组件中,每行通过HStack放置两个按钮,点击任意一个按钮时,两个按钮的action都会被触发,而非仅触发被点击的那个。

原始代码

struct NineView: View {
    var body: some View {
        List {
            ForEach(0..<5) { item in
                getContent()
            }
        }
    }
    
    @ViewBuilder
    func getContent() -> some View {
        DoubleView {
            print("h1")
        } action2: {
            print("h2")
        }
    }
}

struct DoubleView: View {
    
    var action1: () -> Void
    var action2: () -> Void
    
    var body: some View {
        HStack() {
            Button {
                action1()
            } label: {
                Text("B1")
            }
            
            Button {
                action2()
            } label: {
                Text("B2")
            }
        }
    }
}

问题原因

这是因为SwiftUI的List行默认带有可点击交互特性,当Button未显式指定buttonStyle时,系统会将整个HStack所在的行识别为一个统一的交互区域,导致点击行内任意位置都会触发所有按钮的action。

解决方案

给两个Button设置明确的buttonStyle即可解决该问题,可根据需求选择.bordered、.plain等样式:

修改后的代码

struct DoubleView: View {
    
    var action1: () -> Void
    var action2: () -> Void
    
    var body: some View {
        HStack() {
            Button {
                action1()
            } label: {
                Text("B1")
            }
            .buttonStyle(.bordered) // 显式指定按钮样式
            
            Button {
                action2()
            } label: {
                Text("B2")
            }
            .buttonStyle(.bordered) // 显式指定按钮样式
        }
    }
}

显式指定按钮样式后,系统会正确识别每个按钮的独立交互区域,避免触发所有action。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 15:57:13