Home > Net >  How to prevent a Menu embedded inside a Button/NavigationLink parent from triggering the parent acti
How to prevent a Menu embedded inside a Button/NavigationLink parent from triggering the parent acti

Time:08-11

If I have a Menu embedded inside of a NavigationLink or a Button, whenever I tap the menu, it also triggers the Button or NavigationLink action. How do I prevent this? A similar implementation of placing buttons inside another button prevents the parent button from triggering.

struct Testing: View {
    var body: some View {
        Button {
            print("DEBUG: Button Action")
        } label: {
            HStack {
                Text("Some Content")
                
                Menu {
                    Button(action: {}) {
                        Label("Save", systemImage: "bookmark")
                    }
                    
                    Button(action: {}) {
                        Label("Block user", systemImage: "x.circle")
                    }
                    
                    Button(action: {}) {
                        Label("Report", systemImage: "flag")
                    }
                }
                label: {
                    Image(systemName: "ellipsis")
                        .frame(width: 30, height: 30)
                }
            }
        }
    }
}

Tapping the ellipse will print("DEBUG: Button Action) AND activate the menu. I would like to implement something that only activates the menu popup.

CodePudding user response:

Remove the menu from the button. The menu will work stand-alone - as Asperi mentioned in the comment, it is also just a kind of button.

You can do it like this:

struct ContentView: View {
var body: some View {
        HStack {
            Text("Some Content")
            
            Menu {
                Button(action: {}) {
                    Label("Save", systemImage: "bookmark")
                }
                
                Button(action: {}) {
                    Label("Block user", systemImage: "x.circle")
                }
                
                Button(action: {}) {
                    Label("Report", systemImage: "flag")
                }
            }
            label: {
                Image(systemName: "ellipsis")
                    .frame(width: 30, height: 30)
            }
        }
    }
}
  • Related