Make a colorful menubar for macOS APP
Create a menubar menu for macOS apps is pretty easy with SwiftUI. Today I will show some simple ways to create a colorful menu with icons and shortcuts.
Let's dive in.
Create a menu with MenuBarExtra
All what we need is adding the following codes to the root view of your SwiftUI app.
MenuBarExtra("OrbitRing", image: "planet") {
// MenuContent
}
And then, add some buttons:
MenuBarExtra("OrbitRing", image: "planet") {
Button {
// TODO: quit app
} label: {
Text(verbatim: "Quit")
}
}
The problem is, we need colorful icons and setup shortcuts for all these options. As a result, we may want to decorate the Button
with:
MenuBarExtra("OrbitRing", image: "planet") {
Button {
// TODO: quit app
} label: {
HStack {
Image("colorfulIcon")
Text(verbatim: "Quit")
}
}
}
It doesn't work, only text, without icon, why?
Modify the MenuBarExtra
style
We just missed an important modifier: .menuBarExtraStyle(.window)
MenuBarExtra("OrbitRing", image: "planet") {
Button {
// TODO: quit app
} label: {
HStack {
Image("colorfulIcon")
Text(verbatim: "Quit")
}
}
}
.menuBarExtraStyle(.window)
The default value for .menuBarExtraStyle
is .menu
.
Add shortcuts for menu items.
It's always a good principle to add shortcuts to item menus. We can easily achieve this with:
MenuBarExtra("OrbitRing", image: "planet") {
Button {
// TODO: quit app
} label: {
HStack {
Image("colorfulIcon")
Text(verbatim: "Quit")
}
}
.keyboardShortcut("q", modifiers: .command)
}
.menuBarExtraStyle(.window)