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

SwiftUI中点击单个按钮却触发两个按钮动作的原因及解决方法

问题原因与解决方法

原因

在SwiftUI的List组件中,未指定样式的Button会默认填充所在行的全部可用空间,加上List行本身的隐式交互特性,导致两个按钮的点击区域实际上覆盖了整个行。点击行内任意位置时,两个按钮的动作都会被触发。

解决方法

给两个按钮添加PlainButtonStyle(),限制按钮仅响应自身文本区域的点击,避免与List行的默认交互冲突:

@State private var sortDirection: SortDirection = .none

List {
    HStack {
        Button("Sort ASC") {
            sortDirection = .asc
            print("ss")
        }
        .buttonStyle(PlainButtonStyle())
        
        Spacer()
        
        Button("Sort DESC") {
            sortDirection = .desc
            print("dd")
        }
        .buttonStyle(PlainButtonStyle())
    }
    
    ForEach(sortedCustomers) { customer in
        Text(customer.name)
    }
}

补充说明

如果你的sortedCustomers是计算属性,确保其依赖列表仅包含sortDirection,避免因不必要的视图重渲染引发异常行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 08:35:34