How do I add a menu bar command in SwiftUI
Asked on 07/29/2024
1 search
To add a menu bar command in SwiftUI, you can use the new NSHostingMenu
class introduced in macOS Sequoia. This allows you to define your menu using SwiftUI views and integrate it seamlessly with AppKit contexts. Here’s a step-by-step guide:
-
Create your menu definition using a SwiftUI view:
- Use SwiftUI views like
Toggle
,Picker
, andButton
to define the menu items.
- Use SwiftUI views like
-
Initialize an
NSHostingMenu
with the SwiftUI view:- This new
NSMenu
subclass allows you to use SwiftUI menus in AppKit contexts.
- This new
-
Use the
NSHostingMenu
in any AppKit context that accepts anNSMenu
:- For example, you can use it with the new
NSPopupButton
initializer that accepts a pull-down menu parameter.
- For example, you can use it with the new
Here is a code snippet to illustrate this:
import SwiftUI
import AppKit
struct MyMenuView: View {
@State private var isToggled: Bool = false
var body: some View {
VStack {
Toggle("Toggle Option", isOn: $isToggled)
Picker("Select Option", selection: $isToggled) {
Text("Option 1").tag(true)
Text("Option 2").tag(false)
}
Button("Perform Action") {
// Action code here
}
}
}
}
let menu = NSHostingMenu(rootView: MyMenuView())
let menuItem = NSMenuItem()
menuItem.submenu = menu
NSApp.mainMenu?.addItem(menuItem)
For more details, you can refer to the session What’s new in AppKit at the 06:41 mark.

Work with windows in SwiftUI
Learn how to create great single and multi-window apps in visionOS, macOS, and iPadOS. Discover tools that let you programmatically open and close windows, adjust position and size, and even replace one window with another. We’ll also explore design principles for windows that help people use your app within their workflows.

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.

SwiftUI essentials
Join us on a tour of SwiftUI, Apple’s declarative user interface framework. Learn essential concepts for building apps in SwiftUI, like views, state variables, and layout. Discover the breadth of APIs for building fully featured experiences and crafting unique custom components. Whether you’re brand new to SwiftUI or an experienced developer, you’ll learn how to take advantage of what SwiftUI has to offer when building great apps.