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

SwiftUI中非同层级手势的排他性响应实现问询

解决SwiftUI手势排他性问题

修改后的代码实现

struct TestView: View {
    var body: some View {
        VStack {
            Text("Should work simultaneously").onTapGesture {
                print("Work simultaneously")
            }
            Text("Should work simultaneously").onTapGesture {
                print("Work simultaneously")
            }
            // 给需要排他处理的视图使用高优先级手势
            Text("Should be exclusive")
                .highPriorityGesture(TapGesture().onEnded {
                    print("Work exclusively")
                })
        }
        .simultaneousGesture(
            TapGesture().onEnded {
                print("Should work everywhere except for 3th child view")
            }
        )
    }
}

逻辑说明

  • 前两个子视图保留原.onTapGesture,会和父视图的.simultaneousGesture同时触发,满足“同时响应”的需求。
  • 第三个子视图替换为.highPriorityGesture,该手势会优先于父视图的.simultaneousGesture被识别,一旦触发自身逻辑,父视图的手势就会被阻断,实现排他性处理。
  • 对应实际项目中的自定义DatePicker,只需将第三个Text替换为你的Picker组件,给它添加.highPriorityGesture处理内部交互,就能实现:点击Picker内部时仅触发Picker自身逻辑(不关闭),点击外部时触发父视图手势执行关闭操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:35:13