- Published on
- 1 min read
> 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
Disable Touches with allowsHitTesting in SwiftUI
Learn how to use the allowsHitTesting modifier to make views ignore touches, letting taps pass through to elements behind them.
Control Tappable Area with contentShape in SwiftUI
Learn how to use the contentShape modifier to expand or customize the tappable area of your SwiftUI views, making buttons and interactive elements more user-friendly.
How to Change the Background Color of a View in SwiftUI
Learn different ways to set background colors on SwiftUI views, from simple color fills to gradients and materials.
// Stay Updated
Get notified when I publish new tutorials on Swift, SwiftUI, and iOS development. No spam, unsubscribe anytime.