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
相关产品推荐
相关产品推荐

