0

I'm trying to create a custom NSView so I can apply that view to my NSStatusBarButton. I want to have 2 small images next to each other inside the view but I can't figure out how I create a custom view that does that. I've tried to simply add one picture to the view but it doesn't show up in the status bar button:

import Cocoa

class statusBarView: NSView {

override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)
    let myimage = NSImage(named:NSImage.Name("StatusBarButtonImage"))
    myimage!.draw(in: dirtyRect)
    }
}

[...]

if let button2 = statusItem2.button {
        button2.addSubview(statusBarView())
    }

Can someone help me out here?

Cemal K
  • 96
  • 8
  • I don't see the "2 small images next to each other" anywhere in your code. – matt May 26 '18 at 22:46
  • hey matt, that's because I first tried it with one image and that didn't even work – Cemal K May 26 '18 at 22:47
  • I don't understand about adding the `statusBarView` as a _subview_ of the status bar button. If you've got an image, why not make it the status bar button's image? – matt May 26 '18 at 22:57
  • hey, that is exactly what I would do if I only wanted to display one image. But the fact that I want a custom view that shows 2 different ones forces me to make my own custom view. At least I've found no other alternative – Cemal K May 26 '18 at 23:00
  • 1
    I still don’t understand. You can easily compose a new NSImage out of your two existing images and set it as the button image. – matt May 26 '18 at 23:09
  • oh, didn't know I could do that. I'll check it out tomorrow, gotta go to bed now but that might solve my problem, thanks! – Cemal K May 26 '18 at 23:14
  • 1
    Probable duplicate of https://stackoverflow.com/questions/2376097/how-to-composite-several-nsimages-into-one-big-image – matt May 26 '18 at 23:20

1 Answers1

1

There are two things I would change.

  • Set the frame for your statusBarView.

if let button2 = statusItem2.button {

    let statusBarView = statusBarView()
    statusBarView.frame = button2.frame
    button2.addSubview(statusBarView)

}

  • Draw in the frame of the view not in the dirtyRect

    myimage!.draw(in: self.frame)

Hope this helps

Marc T.
  • 5,090
  • 1
  • 23
  • 40
  • Thanks, that works too but I'll go with matts suggestion because then I can also set the image as template image (which I really need). Setting it in my custom view with myimage?.isTemplate = true didn't work unfortunately – Cemal K May 28 '18 at 04:59