Skip to content
DeveloperMemos

Implementing a Context Menu in SwiftUI(After Longpress)

SwiftUI, iOS, User Interface1 min read

Creating intuitive and interactive user interfaces is a key aspect of iOS app development. SwiftUI, Apple's innovative UI toolkit, allows for simple yet powerful UI design. In this guide, we'll explore how to implement a context menu that is triggered by a long press gesture in SwiftUI.

Prerequisites

Before we start, ensure you have the following:

  • Xcode installed on your Mac
  • Basic knowledge of SwiftUI

Step-by-Step Implementation

1. Create a New SwiftUI View

First, let's start by creating a new SwiftUI View where we will implement our context menu.

1import SwiftUI
2
3struct ContentView: View {
4 var body: some View {
5 Text("Long Press for Options")
6 .padding()
7 }
8}

2. Adding the Context Menu

To add a context menu, we use the .contextMenu modifier. This modifier should be attached to the view that will trigger the menu. In our case, it's the Text view.

1Text("Long Press for Options")
2 .padding()
3 .contextMenu {
4 Button("Option 1", action: performOption1)
5 Button("Option 2", action: performOption2)
6 Divider()
7 Button("Cancel", action: {})
8 }

3. Implementing the Actions

Now, let's define the actions that will be triggered when the menu options are selected.

1func performOption1() {
2 print("Option 1 selected")
3}
4
5func performOption2() {
6 print("Option 2 selected")
7}

UI Screenshot

4. Customizing the Menu

You can customize the menu by adding images or changing text styles. Let's add an icon next to our menu options with the Label view.

1Button(action: performOption1) {
2 Label("Option 1", systemImage: "1.circle")
3}
4Button(action: performOption2) {
5 Label("Option 2", systemImage: "2.circle")
6}

Wrapping Up

Remember, SwiftUI is highly customizable, and you can further enhance this functionality with animations, different gestures, and more complex actions. This kind of menu is great if you want to give a user various options after holding down on a UI item, I actually just realized the other day that the Twitter app uses context menus too. Anyway, happy coding!