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

SwiftUI macOS List添加双击TapGesture后选中功能异常问题

macOS 平台 SwiftUI List 双击手势冲突问题

问题描述

在macOS平台基于SwiftUI实现List组件时,为列表行添加双击TapGesture会破坏列表原生选中逻辑:

  • 点击列表项文本外侧区域可正常选中项
  • 直接点击文本内容区域无法触发选中
  • 注释掉TapGesture相关代码后,列表选中功能即可恢复正常

复现代码

struct Item: Identifiable, Hashable {
    var id: String { name }
    let name: String
}

class Manager: ObservableObject {
    
    @Published var data = [Item]()
    @Published var selection = Set<Item>()
    
    init() {
        data = [
            .init(name: "TextTextTextTextTextTextTextText-A"),
            .init(name: "TextTextTextTextTextTextTextText-B"),
            .init(name: "TextTextTextTextTextTextTextText-C"),
            .init(name: "TextTextTextTextTextTextTextText-D"),
            .init(name: "TextTextTextTextTextTextTextText-E")
        ]
    }
}

struct ContentView: View {
    
    @ObservedObject var manager = Manager()
    @State var selection = Set<Item>()
    
    var body: some View {
        List(manager.data, id: \.self, selection: $selection) { item in
            Text(item.name)
                .gesture(TapGesture(count: 2).onEnded {
                    print("Double clicked", item.name)
                })
        }
        .padding()
    }
}

问题效果演示

点击行为异常演示

现有临时规避方案

目前可行的临时规避方案是使用simultaneousGesture,但通过selection = Set([item])手动设置选中状态的实现方式较为冗余笨拙:

List(manager.data, id: \.self, selection: $selection) { item in
    Text(item.name)
        .gesture(TapGesture(count: 2).onEnded {
            print("Double clicked", item.name)
        })
        .simultaneousGesture(TapGesture().onEnded {
            selection = Set([item])
        })
}

补充验证结论

经测试验证:如果selection类型为Set<String>而非Set<Item>(即列表数据源直接使用String类型,而非自定义Item模型),列表选中功能可正常运行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 10:06:34