How to show a context menu in SwiftUI?

Uplift iOS Interview

The Guide is for YOU if
  • You are preparing for an iOS interview and want to improve your skills and knowledge and looking to level up your interview game and land your dream job.
  • You want to gain confidence and ease during iOS interviews by learning expert tips and curated strategies.
  • You want access to a comprehensive list of iOS interview QA to practice and prepare.

The context menu provides you access to additional functionality related to onscreen items without cluttering the screen. You can create a context menu using .contextMenu modifier. The context menu is triggered with a long press. Each menu item in the context menu represents a SwiftUI button. You can add action, text and icon on those buttons.

struct ContentView: View {
   var body: some View {
        Text("Long press for menu")
            .contextMenu {
                Button {
                    print("Pills selected")
                } label: {
                    Label("Pills", systemImage: "pills")
                }

                Button {
                    print("Heart selected")
                } label: {
                    Label("Heart rate", systemImage: "heart")
                }

                Button {
                    print("ECG selected")
                } label: {
                    Label("ECG", systemImage: "waveform.path.ecg")
                }
            }
    }
}

Here, we have a context menu with three buttons. You can use the “Long press for menu” to reveal a context menu. When open, a context menu displays a preview of the item and lists the commands that act on it. It is recommended to place the most frequently used menu items at the top of the menu.



✍️ Written by Ishtiak Ahmed

👉 Follow me on XLinkedIn



Get Ready to Shine: Mastering the iOS Interview




Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book.

If you know someone who would benefit from reading this article, please share it with them.