Creating a macOS Statusbar Application
In this post we will create a macOS statusbar application. In order to follow this tutorial you will need following items:
- A device that is capable of running macOS Big Sur
- Xcode (I am using Version 13.2.1 (13C100))
- Open Xcode and create new project.
- Select App under macOS platform
- Enter your product name (Statusbar)
- Select Team if you have one or let Xcode generate one (My developer account)
- Enter an organization identifier (Reverse domain — dev.gokhun)
- Select SwiftUI as interface and Swift as language
- Uncheck core data and tests for now
In order to add statusbar and menu items we need to add
NSApplicationDelegate to our application.
Right click to
Statusbar folder in project navigator and create a new swift file:
StatusbarApp.swift file and fill with followings:
NSApplicationDelegateAdaptorwill let us use
AppKit in our SwiftUI based application. Since our application will be in statusbar we will not use
WindowGroup. Instead we will use
Settings which will give us a preferences menu bar item.
AppDelegate.swift file and override
applicationDidFinishLaunching method to add statusbar item:
Finally we need to add a property to our target. Open Xcode and select the top item in Project navigator. Then select
TARGETS menu and navigate to
Application is agent (UIElement) YES as seen in screen shot above. This makes our application run in background and do not populate the menu bar (File, edit, view … items near apple logo).
At this stage we should have a star with a single menu item in our statusbar.
In order to make our statusbar application more useful let’s open some windows from statusbar items programmatically. We will create
NSWindow instances by clicking statusbar menu items. In these windows we will use SwiftUI elements.
First create a SwiftUI view with following content:
Add following function to
To call this function we will add a selector to our statusbar item:
AppDelegate.swift file looks like this:
Here is the final result:
- We have used an adapter to add AppKit to our SwiftUI application.
- We have used another adapter to call SwiftUI view from AppKit NSWindow.
- We have set application target property to run it in background
Source code for this application can be found in GitHub
Originally published at https://gokhun.dev on December 27, 2021.