objective-cmacoscocoansstatusitemnsstatusbar

OSX Status Bar Image Sizing - Cocoa


So i'm having a problem with the image of a NSStatusBar item, it seems like the image is pushing away from the rest of the menu items as you can see in this picture. But when the menubar is inactive (as in i'm on my other monitor or not in the app) the problem doesn't happen as you can see in this picture. I'm pretty sure that my code is correct though.

statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
[statusItem setHighlightMode:YES];
[statusItem setAction:@selector(openWindow)];
[statusItem setTarget:self];

if ([[[NSAppearance currentAppearance] name] containsString:NSAppearanceNameVibrantDark]) {
    [statusItem setImage:[NSImage imageNamed:@"whiteMenu.png"]];
} else {
    [statusItem setImage:[NSImage imageNamed:@"blackMenu.png"]];
}

I viewed this question: Display image in a cocoa status app but the problem persists, so i'm not sure what else to do, thanks for any help! PS: The problem i think is the NSVariableStatusItemLength, i tried NSSquareStatusItemLength but with no luck, also tried setting it myself, but with the same problem, but with little improvement.


Solution

  • I also had several problems when implementing a good looking NSStatusItem that is displayed in the menu bar.
    I got the best results when the following criteria were met for the item (and the accompanying asset)

    This snippet will give you a basic application with a nice looking NSStatusItem in the system main menu (I used a system provided image here, but you can get the same results with a custom 18x18 PDF with a "Template" name suffix):

    @interface AppDelegate ()
    
    @property NSStatusItem* statusItem;
    @property (weak) IBOutlet NSMenu *statusMenu;
    
    @end
    
    @implementation AppDelegate
    
    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSImage* statusImage = [NSImage imageNamed:NSImageNameActionTemplate];
        statusImage.size = NSMakeSize(18.0, 18.0);
        self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
        self.statusItem.image = statusImage;
        self.statusItem.highlightMode = YES;
        self.statusItem.enabled = YES;
        self.statusItem.menu = self.statusMenu;
    }
    
    - (void)applicationWillTerminate:(NSNotification *)aNotification {
        // Insert code here to tear down your application
    }
    
    @end