swiftswiftui
SwiftUI Menu Components: Smart Context Actions with Dynamic Content
Daily tips and best practices
Tip
Use
Menu
with @ViewBuilder
closures to create context-sensitive actions that adapt based on current state. Pro tip: nest Menu
components to create hierarchical action menus that feel native and intuitive.Best Practice: Implement Role-Based Menu Actions for Better UX
This pattern uses semantic button roles and logical grouping with dividers to create intuitive menu hierarchies. The destructive action is clearly separated and confirmed with an alert, while related actions are grouped together in submenus.
struct DocumentMenu: View {
let document: Document
@State private var showingDeleteAlert = false
var body: some View {
Menu {
Button("Edit", systemImage: "pencil") {
editDocument()
}
Button("Share", systemImage: "square.and.arrow.up") {
shareDocument()
}
Divider()
Menu("More Options") {
Button("Duplicate", systemImage: "doc.on.doc") {
duplicateDocument()
}
Button("Export", systemImage: "arrow.up.doc") {
exportDocument()
}
}
Divider()
Button("Delete", systemImage: "trash", role: .destructive) {
showingDeleteAlert = true
}
} label: {
Image(systemName: "ellipsis.circle")
.foregroundColor(.secondary)
}
.alert("Delete Document?", isPresented: $showingDeleteAlert) {
Button("Delete", role: .destructive) {
deleteDocument()
}
Button("Cancel", role: .cancel) { }
}
}
}
Why This is a Best Practice
Role-based menu design improves accessibility by providing semantic meaning to screen readers, while logical grouping reduces cognitive load. Separating destructive actions prevents accidental deletions and follows Apple's Human Interface Guidelines for safe user interactions.
History
Loading...