- Published on
Detect when a context menu is open in SwiftUI
- Authors

- Name
- Mick MacCallum
- @0x7fs
SwiftUI doesn't provide a built-in way to detect when a context menu is open. There are some common workarounds to this problem like using gesture recognizers, but these can break the scrolling behavior of the context view. The best solution I've found is to use the onAppear and onDisappear modifiers on one of the children of the context menu, to update a state variable that we can use to trigger actions.
struct ContentView: View {
@State private var isOpen = false
var body: some View {
Text("Demo Menu")
.contextMenu(menuItems: {
Button("First Button") {
// action
}
.onAppear {
print("The menu is open!")
isOpen = true
}
.onDisappear {
print("The menu is closed!")
isOpen = false
}
Button("Second Button") {
// action
}
})
}
}
Continue Learning
Prevent Drag-to-Dismiss on SwiftUI Sheets
Learn how to prevent users from dismissing modal sheets by swiping down in SwiftUI using interactiveDismissDisabled.
Add Spacing to Toolbars with ToolbarSpacer in SwiftUI
Learn how to use ToolbarSpacer to add fixed and flexible spacing between toolbar items in SwiftUI, new in iOS 26.
Control Sheet Height with presentationDetents in SwiftUI
Learn how to use the presentationDetents modifier to control sheet heights in SwiftUI, creating interactive bottom sheets similar to Apple Maps and Music.
