Swift 6 + iOS 18下Menu组件onTapGesture及primaryAction失效求助
升级至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
相关产品推荐
相关产品推荐

