Search code examples
swiftmenu

What is the object type that handles true application Menu Bars?


I don't want to use Obj C I want to use native Swift menu's in the standard menu bar. Like these:

Safari Menu

The code examples that I find keep doing standard toolbar menu's. I'm not writing an iOS application, I'm writing a standard Mac application. I'm trying to keep things very simple. I've tried putting in a .menu which is what somebody suggested and also tried: Menu("Actions") { Button("do X", ... ), but .menu is not allowed in a Scene and Menu() does not 'conform'.

On a related note I have created my toolbars already and I'm trying to set-up a design pattern where I can put any menu anywhere. So font menus (font, size etc) can be in a context menu or in a standard application menu. Basically designing the UI first then adding functionality. I'll be writing two applications at the same time and I'm trying to get consistency between them.


Solution

  • The menu in your picture is the commands menu.

    It is accessed via

    .commands(content:)
    

    https://developer.apple.com/documentation/swiftui/scene/commands(content:)

    https://developer.apple.com/wwdc20/10041

    @main
    struct BookClubApp: App {
        var body: some Scene {
            WindowGroup {
                List {
                    Text("Reading List Viewer")
                }
            }
            .commands {
                Button("Previous Book", action: selectPrevious)
                    .keyboardShortcut("[")
                Button("Next Book", action: selectNext)
                    .keyboardShortcut("]")
            }
        }
    
        private func selectPreviousBook() {}
        private func selectNextBook() {}
    }