Understanding Menus in SwiftUI

Introduction to SwiftUI Menus

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.

Basic Syntax of a Menu

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.

Menu Content Types

Inside a Menu, you can place:

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)
    }
}

Customizing Menus

Adding Icons to Buttons in Menu

Menu("More Options") {
    Button {
        duplicateItem()
    } label: {
        Label("Duplicate", systemImage: "doc.on.doc")
    }
    Button {
        renameItem()
    } label: {
        Label("Rename", systemImage: "pencil")
    }
}

Custom Menu Labels

Menu {
    Button("New File", action: newFile)
    Button("Open File", action: openFile)
} label: {
    Label("File", systemImage: "folder")
        .font(.title)
        .foregroundColor(.blue)
}

Using Roles for Buttons in Menus

Menu("Account") {
    Button("Sign Out", role: .destructive, action: signOut)
    Button("Cancel", role: .cancel, action: cancelOperation)
}

Nested Menus (Submenus)

Menu("Settings") {
    Button("Profile", action: openProfile)
    Menu("Notifications") {
        Button("Push Notifications", action: openPushSettings)
        Button("Email Notifications", action: openEmailSettings)
    }
    Button("Privacy", action: openPrivacySettings)
}

Advanced Example: Fully Customized Menu Button

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)
}

Notes and Best Practices

Conclusion

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.