BS
BleepingSwift
Published on
1 min read

> Detect when a context menu is open in SwiftUI

Share:

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.

Swift
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
                }
            })
    }
}
subscribe.sh

// Stay Updated

Get notified when I publish new tutorials on Swift, SwiftUI, and iOS development. No spam, unsubscribe anytime.

>

By subscribing, you agree to our Privacy Policy.