0

I was working on my menu bar app and made the NSStatusBarButton look like I want. Then I restructured the code a bit and suddenly after running it without any compiler errors/warnings, the button doesn't show up in the menu bar anymore.

I've already checked my code twice but I don't find the reason why it changes its behaviour. Now the curious part is, that if I go ahead an copy paste my code into a newly created cocoa app project, it works just fine again. Wtf? Did I mess up my project settings somehow? But that can't really be. I've literally just put the code that draws the button image from the applicationDidFinishLaunching method to a seperate one that I called initStatusBarImage() and called it from applicationDidFinishLaunching. Then it suddenly doesn't show the status bar item, I undo the code changes, run it and it still doesn't work. Am I missing something important? Here's a sample code I have issues with as described. And yes, the image is in my assets folder, that's not the problem

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    let sItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.variableLength)
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        let img1 = NSImage(named:NSImage.Name("progressbar-15"))
        let img2 = NSImage(named:NSImage.Name("progressbar-15"))
        let img3 = NSImage(size: NSSize(width: 20, height: 18))
        img3.lockFocus()
        img1?.draw(at: NSPoint(x: 0, y: 0), from: NSZeroRect, operation: NSCompositingOperation.sourceOver, fraction: 1.0)
        img2?.draw(at: NSPoint(x: 10, y: 0), from: NSZeroRect, operation: NSCompositingOperation.sourceOver, fraction: 1.0)
        img3.unlockFocus()
        if let but = sItem.button {
            but.image = img3
        }
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

}
Blaise
  • 13,139
  • 9
  • 69
  • 97
Cemal K
  • 96
  • 8
  • "the button doesn't show up in the menu bar" You have set the image of sItem.button. That's all you have done. – El Tomato May 28 '18 at 21:28
  • Yes, but that's how it works, right? I've seen it in more than one tutorial. I just set the button's image and text of the statusItem and the changes should take effect without any other action of mine. Right now, I think that ARC is deallocating my button or statusItem object immediately because I don't use it anywhere else in the code after I initialize it, but I'm not sure – Cemal K May 29 '18 at 08:26
  • If the item is removed from the bar by the user (Cmd+drag on macOS), you will have to set `sItem.visible = YES`; otherwise, the item will not reappear. – Eric Reed Mar 02 '20 at 12:37

0 Answers0