2

I'm looking for a way to put a ProgressBar onto the Mac status bar as a button. I want to have something like this:

Sample Image

or

enter image description here

What I can do is this:

    let statusItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.variableLength)

    [...]

    if let button = statusItem.button {
                button.image = NSImage(named:NSImage.Name("JustSomeImage"))
                button.title = "Hello"
                button.action = #selector(togglePopover(_:))

            }

But with NSStatusItem, I'm limited to only use a button and menu object to manipulate my NSStatusBar. So all I can do is putting an image to the bar with some text. I have searched a lot for a solution and read the doc, but I couldn't find a way to put a ProgressBar up there somehow. Anyone has an idea how I could do that?

Cemal K
  • 96
  • 8

1 Answers1

3

Since NSButton is a subclass of NSView you can add any view you would like to add. Below you can find a small code snippet in Objective C but it should not be difficult to turn it into Swift.

NSProgressIndicator *indicator = [[NSProgressIndicator alloc] initWithFrame:button.frame];
[button addSubview:indicator];

Best wishes and great success.

Marc T.
  • 5,090
  • 1
  • 23
  • 40
  • Thanks, that helps. Can you also tell me how I can do something similar like on the picture on the main post? I have no idea what kind of component I'd need to use to draw that. I could just add the labels "CPU" and "MEM" as images but the progress bar I can't figure out – Cemal K May 20 '18 at 20:38
  • 1
    There are different options how to do so. Custom drawing in NSView by using NSBezierPath or using different NSImages and displaying them dependent of the level of the gauge. Since the icons are not to complex I would use the first approach. First drawing a rect and a line with a increased line width in the middle. https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CocoaDrawingGuide/Paths/Paths.html – Marc T. May 21 '18 at 03:42
  • Hey, I've tried the first approach but I already failed at trying to fill in the rectangle with a specified color. Also, when choosing NSStatusItem.variableLength, it doesn't seem to adjust the length of the NSStatusItem. Even with my NSRect's width set to >100, it stays at ~20 (I don't even know the metric). Now I wanna try the other way of just making some images with ~10% intervals of the progressbar. Though my question now is, how can I add 2 images into a single NSView? Sorry if I'm bothering you, but I can't find enough doc/code samples on the internet regarding this – Cemal K May 21 '18 at 17:47