Menu in SwiftUI is a control used to present menu of actions. Menu control can be built with Button, Text, Link, Label, Image and Divider views.
Let’s explore more with example.
struct DevTechieMenuExample: View {
@State private var selectedAction = "circle.slash"
var body: some View {
VStack {
Text("DevTechie")
.font(.largeTitle)
.foregroundColor(.white)
.padding(.vertical, 10)
.frame(maxWidth: .infinity)
.background(.orange)
Spacer()
Menu("Actions") {
Button("Cut") {
selectedAction = "scissors"
}
Button("Copy") {
selectedAction = "doc.on.doc"
}
Button("Paste") {
selectedAction = "doc.on.clipboard"
}
}
Image(systemName: selectedAction)
.font(.system(size: 42))
Spacer()
}
}
}
Menu can have another Menu view as child view.
Menu("Actions") {
Button("Cut") {
selectedAction = "scissors"
}
Button("Copy") {
selectedAction = "doc.on.doc"
}
Menu("Paste") {
Button("Paste") {
selectedAction = "doc.on.clipboard"
}
Button("Paste Special") {
selectedAction = "doc.on.clipboard.fill"
}
}
}
Another overload of Menu provides a view builder closure to build custom view.
Menu {
Button("Cut") {
selectedAction = "scissors"
}
Button("Copy") {
selectedAction = "doc.on.doc"
}
Menu("Paste") {
Button("Paste") {
selectedAction = "doc.on.clipboard"
}
Button("Paste Special") {
selectedAction = "doc.on.clipboard.fill"
}
}
} label: {
Image(systemName: "rectangle.and.pencil.and.ellipsis")
Text("Copy Pasta")
}
Notice the order of Menu options don’t appear the way we have them in code. We can fix it with the help of menuOrder modifier.
fixed: order items from top to bottom
.menuOrder(.fixed)
Other options are priority and automatic.
priority: keeps the first items closest to user’s interaction point.
automatic: The ordering of the menu is chosen by the system for the current context. On iOS, this order resolves to fixed .
We can create pickers in Menu.
Menu("Copy Pasta") {
Picker(selection: $selectedAction, label: Text("select")) {
Text("Cut").tag("scissors")
Text("Copy").tag("doc.on.doc")
Text("Paste").tag("doc.on.clipboard")
}
}
.menuOrder(.priority)
We can even create sections for Menu options.
Menu("Copy Pasta") {
Section("Copy") {
Picker(selection: $selectedAction, label: Text("select")) {
Text("Cut").tag("scissors")
Text("Copy").tag("doc.on.doc")
}
}
Section("Paste") {
Picker(selection: $selectedAction, label: Text("select")) {
Text("Paste Special").tag("doc.on.clipboard.fill")
Text("Paste").tag("doc.on.clipboard")
}
}
}
With that we have reached the end of this article. Thank you once again for reading. Don’t forget to follow 😍. Also subscribe our newsletter at https://www.devtechie.com