Creating context menus
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 the touch-and-hold gesture in iOS and iPadOS and a control click on macOS. Context menus consist of a collection of buttons displayed horizontally in an implicit VStack
.
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 DisplayingContextMenus
.
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 a @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 inContentView.swift
, add a@State
variable to hold the color of the bulb. Initialize it tored
:
...@State private var bulbColor = Color.red