How do I add context menus and previews on watchOS using Swift?

In watchOS, you can enhance user interactions by adding context menus and previews to your app. Context menus allow users to perform actions related to the content displayed on the screen, while previews provide quick access to more information without navigating away from the current view.

Adding Context Menus

To create a context menu in watchOS, you can use the contextMenu modifier on a SwiftUI view. Here's a simple example of how to implement a context menu with a few actions:

struct ContentView: View { var body: some View { VStack { Text("Tap and hold to see the context menu") .contextMenu { Button(action: { print("Action 1 selected") }) { Text("Action 1") Image(systemName: "star") } Button(action: { print("Action 2 selected") }) { Text("Action 2") Image(systemName: "trash") } } } } }

Adding Previews

To provide a preview of content, you can use the previewContextMenu modifier. This feature allows users to peek at more details when they press firmly on an item.

struct ItemView: View { var item: String var body: some View { Text(item) .previewContextMenu { Button(action: { print("\(item) details selected") }) { Text("Preview Details") } } } }

watchOS SwiftUI context menus previews user interaction