How to open Menu only on long press gesture SwiftUI

Viewed 3184

Is there a way to show context menu on long press gesture in SwiftUI?

I have a code like this:

Text(messageModel.message)
  .padding(.vertical,8)
  .padding(.horizontal,12)
  .background(Constants.clientMessageColor)
  .foregroundColor(Color.black)
  .cornerRadius(20, corners: [.topLeft,.bottomLeft,.topRight, .bottomRight])
  .onTapGesture {
       self.isExpanded.toggle()
       self.isClientNameVisible.toggle()
  }
  .contextMenu {
       Button(action: {
                                        
       }) {
             Text("Normal Colors")
             Image(systemName: "paintbrush")
       }
   }

And also I use Menu in SwiftUI and also don't know how to show in long press.

My code look like this:

Menu() {
    Button("Order Now", action: {})
    Button("Adjust Order", action: {})
    Button("Cancel", action: {})
} label : {
    Text("HELLO")
        .onLongPressGesture {
            // Show menu when this triggers
        }
}
1 Answers

Here is a simple demo (for clarity, menuItems extracted outside the body):

struct ContentView: View {
    var body: some View {
        VStack {
            Text("On long press")
                .contextMenu {
                    menuItems
                }
            Menu("On tap") {
                menuItems
            }
        }
    }
    
    var menuItems: some View {
        Group {
            Button("Action 1", action: {})
            Button("Action 2", action: {})
            Button("Action 3", action: {})
        }
    }
}
Related