Creating a context menu
A context menu is a pop-up menu used to display actions that the developer anticipates the user might want to take. SwiftUI context menus are triggered using 3D Touch on iOS and a right-click on macOS.
A context menu consists of a collection of buttons displayed horizontally in an implicit HStack.
In this recipe, we will create a context menu to change the color of an SF symbol.
Getting ready
Create a new SwiftUI project named ContextMenuApp
.
How to do it
We will display a light bulb in our view and change its color using a context menu. To achieve this, we'll need to create an @State
variable to hold the current color of the bulb and change its value within the context menu. The steps are as follows:
- Just above the body variable in
ContentView.swift
, add an@State
variable to hold the color of the bulb. Initialize it tored
:@State private var bulbColor = Color.red
- Within the body variable, change the
Text
struct to anImage...