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

Swift 6 + iOS 18下Menu组件onTapGesture及primaryAction失效求助

问题:iOS 18/Swift 6下Menu组件点击交互异常,无法同时触发自定义动作与弹出菜单

升级至Swift 6与iOS 18后,Menu组件的onTapGesture被默认交互拦截无法触发,使用primaryAction则会覆盖弹出菜单的行为,导致点击时仅触发动作但菜单不弹出。

解决方案

方案1:使用simultaneousGesture让手势与Menu默认交互共存

通过simultaneousGesture添加点击手势,让自定义动作与Menu的默认弹出行为同时触发:

Menu {
    Button(action: {}) {
        Label("Add to Reading List", systemImage: "eyeglasses")
    }
    Button(action: {}) {
        Label("Add Bookmarks for All Tabs", systemImage: "book")
    }
    Button(action: {}) {
        Label("Show All Bookmarks", systemImage: "books.vertical")
    }
} label: {
    Label("Add Bookmark", systemImage: "book")
}
.simultaneousGesture(TapGesture().onEnded {
    print("Tap gesture recognized")
})

方案2:手动控制Menu的展示状态

通过绑定isPresented属性,在自定义点击动作中手动触发菜单弹出:

struct ContentView: View {
    @State private var isMenuPresented = false
    
    var body: some View {
        Menu(isPresented: $isMenuPresented) {
            Button(action: {}) {
                Label("Add to Reading List", systemImage: "eyeglasses")
            }
            Button(action: {}) {
                Label("Add Bookmarks for All Tabs", systemImage: "book")
            }
            Button(action: {}) {
                Label("Show All Bookmarks", systemImage: "books.vertical")
            }
        } label: {
            Label("Add Bookmark", systemImage: "book")
        }
        .onTapGesture {
            print("Custom tap action triggered")
            isMenuPresented = true
        }
    }
}

原因说明

在iOS 18/Swift 6中,Menu组件的交互逻辑发生了调整:

  • 直接添加的onTapGesture会被Menu内部的默认点击事件拦截,无法触发;
  • primaryAction的设计初衷是替代默认的弹出行为,触发自定义动作后不会自动弹出菜单。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 23:32:08