Search code examples
swiftmacoscocoastatusbarnsview

Draw 2 Images in NSView


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?


Solution

  • 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