How to display a Menu in SwiftUI
Displaying menus as pop-ups when pressing a button is very easy in SwiftUI thanks to its Menu
view. Let’s see an example of how to create a menu with different options:
import SwiftUI
struct ContentView: View {
var body: some View {
// 1
Menu("Teams") {
// 2
Button("Real Madrid", action: {})
Button("Barcelona", action: {})
Button("Chelsea", action: {})
Button("Manchester City", action: {})
}
}
}
- We use the
Menu
view, which takes aLocalizedStringKey
as a parameter, which serves as the title of our button. - We create the different options that our menu will have.
By using
LocalizedStringKey
, the app will automatically support the translations we have in our String Catalog.
Using a Menu Within a Menu (Inception? 🤔)
It is possible to create a menu within another menu; simply, among the options, instead of using a Button
, we use another Menu
. Let’s see how:
Menu("Teams") {
Menu("Real Madrid") {
Button("Real Madrid", action: {})
Button("Real Madrid Castilla", action: {})
}
Button("Barcelona", action: {})
Button("Chelsea", action: {})
Button("Manchester City", action: {})
}
Customizing the Menu Label
If instead of a simple string
you want more control over how the Menu label looks, we can use another of its constructors init(content:label:)
. Let’s see how:
Menu {
Menu("Real Madrid") {
Button("Real Madrid", action: {})
Button("Real Madrid Castilla", action: {})
}
Button("Barcelona", action: {})
Button("Chelsea", action: {})
Button("Manchester City", action: {})
} label: {
// 1
Label("Teams", systemImage: "soccerball")
}
- In this section, we will add whatever we want the Menu label to show. In our case, we are using a
Label
to display a title and an icon.
Creating Different Sections Within the Menu
We can use the Section
view to group options within sections inside our Menu
. Let’s see an example:
Menu {
// 1
Section("Football") {
Menu("Real Madrid") {
Button("Real Madrid", action: {})
Button("Real Madrid Castilla", action: {})
}
Button("Barcelona", action: {})
}
Section("Basketball") {
Button("Lakers", action: {})
}
Section("Baseball") {
Button("Chicago Cubs", action: {})
}
} label: {
Text("Teams")
}
- Simply add the options we want inside
Section
, and we can have different sections grouped as options of theMenu
.
How to Use Primary Action in a Menu
Starting from iOS 15, we can add a default action when opening the menu using the init(content:label:primaryAction:)
constructor. Let’s see an example:
Menu {
Menu("Real Madrid") {
Button("Real Madrid", action: {})
Button("Real Madrid Castilla", action: {})
}
Button("Barcelona", action: {})
} label: {
Text("Teams")
} primaryAction: {
// 1
print("Action called")
}
- We see the use of the new constructor, where we execute whatever we want as the primary action once the
Menu
is opened.