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
In this recipe, we will create a context menu to change the color of an SF symbol.
Create a new SwiftUI project named
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
@Statevariable to hold the color of the bulb. Initialize it to
@State private var bulbColor = Color.red
- Within the body variable, change the
Textstruct to an