2

I've been trying to make a custom view for a NSMenuItem with an image on it. The code below overrides the original view, but without the image. The item appears blank and smaller.

This code is only an example!

class CustomItemView: NSView {
    private let imageView: NSImageView = NSImageView()
    
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        
        // self.imageView.frame = frameRect
        self.imageView.image = NSImage.init(named: "example")!
        self.addSubview(self.imageView)

        self.imageView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
            self.imageView.centerYAnchor.constraint(equalTo: self.centerYAnchor),
            self.imageView.widthAnchor.constraint(equalToConstant: 100),
            self.imageView.heightAnchor.constraint(equalToConstant: 100)
        ])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

I then simply add set the view like this

let newItem: NSMenuItem = NSMenuItem()
newItem.view = CustomItemView()
newItem.target = self
self.addItem(newItem)
Alexandra
  • 39
  • 6

0 Answers0