charelf
charelf

Reputation: 3815

SwiftUI detect when contextMenu is open

As the title says, is there any way I can detect (e.g. using a @State variable) when either any context menu is open, or the context menu of a specific view is open?

As a basic idea, I would like to print something if it is open. This does not work:

.contextMenu {
   print("open")
}

This also does not seem to work:

.contextMenu {
    EmptyView()
    .onAppear {
        print("open")
    }
}

How could i make this work?


Edit: Why i think its even possible to do it or at least possible to make it look like its possible: On instagram, one can see individual posts as a square only. However using long-press, a context menu opens, and now the post shape is different, but even more there is also a small title above it.. How would one do that? Did they modify the view when the context menu open or is the grid view the post is in before just hiding those details (true image shape + image title) but they are rendered already?

Screenshots:

enter image description here enter image description here

Upvotes: 6

Views: 3220

Answers (1)

Asperi
Asperi

Reputation: 257711

A possible approach is to use simultaneous gesture for this purpose, like

Text("Demo Menu")
    .contextMenu(menuItems: {
        Button("Button") {}
    })
    .simultaneousGesture(LongPressGesture(minimumDuration: 0.5).onEnded { _ in
        print("Opened")
    })

Tested with Xcode 13.2 / iOS 15.2

Upvotes: 4

Related Questions