Skip to content

SwiftUI Menus and Commands

SwiftUI offers a robust framework for building interactive and user-friendly menus. These components are crucial for apps requiring complex navigation structures and command options. We’ll explore each component and provide practical examples.

1. Menu

The Menu view in SwiftUI is used to present a list of actions or options in a contextual popup. It is particularly useful for conserving screen space while offering multiple choices.

Example of Creating a Basic Menu:

struct MenuExampleView: View {
    var body: some View {
        Menu("Options") {
            Button("Print Hello", action: printHello)
            Button("Show Alert", action: showAlert)
        }
    }
    
    func printHello() {
        print("Hello")
    }
    
    func showAlert() {
        print("Alert should be shown here")
    }
}

2. Commands

Commands allow the addition of custom command menus and keyboard shortcuts to your SwiftUI app, enhancing functionality especially for macOS and iPadOS apps.

The .commands modifier is specific to macOS and iPadOS development within SwiftUI. It allows you to customize the menu bar on macOS and the Command menu that appears in the app switcher on iPadOS when a keyboard is connected.

Example of Adding Commands:

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .commands {
            CommandGroup(replacing: .newItem) {
                Button("New Dashboard") {
                    print("Create new dashboard")
                }
            }
        }
    }
}

3. MenuOrder and MenuActionDismissBehavior

MenuOrder determines the order in which menu items appear, helping prioritize the most important actions. MenuActionDismissBehavior specifies whether an action should dismiss the menu when triggered.

You can also use this modifier with Picker to disable dismissal.

Example of Customizing Menu Order and Dismiss Behavior:

struct AdvancedMenuView: View {
    var body: some View {
        Menu("Advanced Options") {
            Button("Refresh", action: refreshContent)
            Button("Load More", action: loadMoreContent)
        }
        .menuStyle(DefaultMenuStyle())
        .menuOrder(.automatic)
        .menuActionDismissBehavior(.dismissReset)
    }
    
    func refreshContent() {
        print("Content refreshed")
    }
    
    func loadMoreContent() {
        print("More content loaded")
    }
}

Conclusion

In this tutorial, we’ve explored how to use Menu, Commands, MenuOrder, and MenuActionDismissBehavior in SwiftUI to enhance app navigation and user interactions. These components provide the tools needed to create detailed and intuitive menus, ensuring a better user experience. By integrating these features into your SwiftUI app, you can significantly improve navigation efficiency and command accessibility, making your app more user-friendly and responsive.

 

Back To Top