In SwiftUI, a Menu is a user interface component that displays a list of actions or options when triggered. It’s ideal for offering users a compact way to access multiple commands without cluttering the main view. Menus automatically adapt their appearance based on the platform (iOS, macOS, watchOS).
Menus are especially useful when you want to group related actions together neatly behind a button or label.
Menu("Options") {
Button("Refresh", action: refreshContent)
Button("Settings", action: openSettings)
Button("Logout", action: logoutUser)
}
Explanation: The Menu
initializer takes a label and a trailing closure that defines the contents inside: typically Button
items.
Inside a Menu
, you can place:
Menu
inside a menu for subcategories.Menu("Actions") {
Button("Edit", action: editItem)
Button("Delete", role: .destructive, action: deleteItem)
Divider()
Menu("Share") {
Button("Share via Email", action: shareEmail)
Button("Share via Messages", action: shareMessages)
}
}
Menu("More Options") {
Button {
duplicateItem()
} label: {
Label("Duplicate", systemImage: "doc.on.doc")
}
Button {
renameItem()
} label: {
Label("Rename", systemImage: "pencil")
}
}
Menu {
Button("New File", action: newFile)
Button("Open File", action: openFile)
} label: {
Label("File", systemImage: "folder")
.font(.title)
.foregroundColor(.blue)
}
Menu("Account") {
Button("Sign Out", role: .destructive, action: signOut)
Button("Cancel", role: .cancel, action: cancelOperation)
}
Menu("Settings") {
Button("Profile", action: openProfile)
Menu("Notifications") {
Button("Push Notifications", action: openPushSettings)
Button("Email Notifications", action: openEmailSettings)
}
Button("Privacy", action: openPrivacySettings)
}
Menu {
Button {
saveFile()
} label: {
Label("Save", systemImage: "square.and.arrow.down")
}
Button(role: .destructive) {
deleteFile()
} label: {
Label("Delete", systemImage: "trash")
}
} label: {
HStack {
Image(systemName: "ellipsis.circle")
Text("Actions")
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
Menus in SwiftUI are a versatile and customizable tool for organizing user interactions efficiently. They help maintain clean interfaces while offering rich functionality. Mastering menus — from basic lists to nested, icon-enhanced structures — will make your SwiftUI apps look professional and feel intuitive to use.