Set the newly created NSMenu as the status bar item's menu.Create an NSMenu which will hold the toggle mute NSMenuItem and any other items that are added in the future.Add an action that will be triggered every time the NSMenuItem is pressed.Create a NSMenuItem to allow users to toggle the mute state.Let's break down the code to understand what's going on: In the AppDelegate.swift, I then implemented the good old applicationDidFinishLaunching method and added the necessary code to create an instance of NSStatusBar with a single NSStatusItem:ĪppDelegate.swift class AppDelegate : NSObject, NSApplicationDelegate Running the application at this point does nothing as the menu bar item has not yet been set up but it can be seen that the app icon does not appear in the dock despite it running! □ Setting up a menu bar icon The app is then started with all command line arguments provided.This prevents the app icon from showing up in the Dock. The app's activationPolicy is set to accessory.An empty AppDelegate class is created and set as the delegate for the NSApplication object.A reference to the application is obtained through the NSApplication object.Let's go through the app startup code above step by step: accessory ) // 4 _ = NSApplicationMain ( CommandLine. Main.swift import AppKit // 1 let app = NSApplication.shared // 2 app.delegate = AppDelegate () // 3 app. ![]() This would still allow me to write SwiftUI code further down the line if I wanted to and it would give me full control over the startup sequence and architecture.įor this reason, I removed all boilerplate SwiftUI code that comes when you create a new macOS app in Xcode and I created a single main.swift file, which would be the new entry point for the application: I decided to use AppKit, as it is easier for me to reason with the bootstrapping code required to make the app work as I want it to and it meant that I did not need to provide a SwiftUI view as an entry point. I thought I would still write my own article on the topic as a reference for my future self and because I have implemented things slightly differently by using entirely AppKit. ![]() I would recommend you go watch them as they do a great job of explaining how a macOS menu bar is set up. Note that there are other amazing resources on the topic such as Mohammad Azam's or Florian Schweizer's videos. ![]() In the following sections, I will go through what my initial steps were to create a menu bar app with no dock icon, with code examples and the reasoning behind my decisions. It will be a menu bar app, called Shush □, which will allow users to mute all their computer's input devices using CoreAudio. This week I have started a journey to develop and (maybe □) release my first ever macOS application.
0 Comments
Leave a Reply. |