How do I add a menu bar command in Swift
Asked on 2024-07-29
1 search
To add a menu bar command in Swift, you can use SwiftUI menus in AppKit contexts by leveraging the NSHostingMenu
, which is a new NSMenu
subclass. Here’s a step-by-step guide on how to do this:
-
Create Your Menu Definition: Define your menu using a SwiftUI view. Use SwiftUI views that best describe the data relationship, such as toggles, pickers, and buttons.
-
Initialize
NSHostingMenu
: Initialize anNSHostingMenu
with your SwiftUI view. -
Use in AppKit Contexts: Use the
NSHostingMenu
in any AppKit context that accepts anNSMenu
, such as the newNSPopupButton
initializer with a pull-down menu parameter.
Here is a code example to illustrate this:
import SwiftUI
import AppKit
struct MyMenu: View {
var body: some View {
Menu {
Button("Action 1", action: performAction1)
Button("Action 2", action: performAction2)
Toggle("Toggle Option", isOn: $toggleOption)
Picker("Pick an Option", selection: $selectedOption) {
Text("Option 1").tag(1)
Text("Option 2").tag(2)
}
} label: {
Text("My Menu")
}
}
@State private var toggleOption = false
@State private var selectedOption = 1
func performAction1() {
// Action 1 code
}
func performAction2() {
// Action 2 code
}
}
let menu = NSHostingMenu(rootView: MyMenu())
For more details, you can refer to the session What’s new in AppKit at the timestamp 06:18.

What’s new in UIKit
Explore everything new in UIKit, including tab and document launch experiences, transitions, and text and input changes. We’ll also discuss better-than-ever interoperability between UIKit and SwiftUI animations and gestures, as well as general improvements throughout UIKit.

Platforms State of the Union 5-Minute Recap
Watch a quick recap of the newest advancements on Apple platforms.

What’s new in AppKit
Discover the latest advances in Mac app development. Get an overview of the new features in macOS Sequoia, and how to adopt them in your app. Explore new ways to integrate your existing code with SwiftUI. Learn about the improvements made to numerous AppKit controls, like toolbars, menus, text input, and more.