avatar
Published on

Detect when a context menu is open in SwiftUI

Authors
  • avatar
    Name
    Mick MacCallum
    Twitter
    @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
                }
            })
    }
}