chipjarred / MacMenuBar

Bringing the Mac Menu Bar into the SwiftUI age.
MIT License
41 stars 3 forks source link

How to add menu items from different file #7

Closed elmcapp closed 2 years ago

elmcapp commented 2 years ago

can you provide a example here how to add a menu item to a menu from two different files

midiManager.swift

class MidiManager {
  //foreach loop to add menu item to a menu
}

macMenuBar.swift

class MainMenuBar: MenuBar {

  // code
}
chipjarred commented 2 years ago

As a design observation, it's probably not a good separation of concerns for your MidiManager to know anything about menus.

That said, I'm not clear on what it is you want to do. You can define menus separately from the menu bar by assigning them to variables, and then just use those variables in the menu bar.

Let's say you have a function, midiDevices(), that returns an Array or some other Sequence of objects representing MIDI devices, you could create a "Devices" menu like this.

let deviceMenu = StandardMenu("Devices”) {
    ForEach(midiDevices()) { 
        TextMenuItem($0.name) { _
            // code for device menu item action handling goes here
        }
    }
}

That stores the "Devices" menu in a variable called deviceMenu, which you can then use in defining the MenuBar. If you do something similar with the application, "File, and "Edit" menus, the menu bar definition would look something like this:

// -------------------------------------
struct MainMenuBar: MenuBar
{
    public var body: StandardMenuBar
    {
        StandardMenuBar
        {
            applicationMenu
            fileMenu
            editMenu
            deviceMenu
        }
    }
}

This can be in a different file from the definitions of applicationMenu, fileMenu, editMenu and deviceMenu.

I do this very thing in the "Soduko" example project. In it the "Themes" menu is dynamically populated, which might be a useful reference for dynamically populating your devices menu. In the Soduko project's folder, look in Sudoku/Menu Bar. Each menu is defined in its own file, as is the menu bar itself.