At WWDC20 this year we received a lot of (awesome) SwiftUI updates, most of which supporting multiple apple platforms. One of my favourite new interactions Apple gave us is the ContenxtMenu view type and .contextMenu view modifier.

Adding a context menu to a button in our interface couldn't be simpler, we use the .contextMenu view modifier and pass in an instance of ContextMenu(menuItems:), who's constructor accepts a closure that returns the content of our menu, let's see this in practice.

In this example we have a View inside a  NavigationView, with a Button as the only navigation item, to attach a context menu to the button all I need to do is add the following.

.navigationBarItems(trailing: Button(action: {
    // Default button action
}, label: {
    Image(systemName: "")
    ContextMenu(menuItems: {
        Button("Menu Item 1", action: {})
        Button("Menu Item 2", action: {})
        Button("Menu Item 3", action: {})

In the live preview click and hold on the button in the navigation bar, the result should look like this.

I really like how this looks and is a welcome new interaction for apps on all of apple's platforms.

Thanks for reading ✌️