swiftmacosnsimageview

macOS - Programmatically display an image using NSImageView


Using a Swift app targeting the macOS platform, I am trying to programmatically create an NSImageView object, assign an image to it, and then display it, using:

let imageViewObject = NSImageView();
let img = NSImage(cgImage: winCGImage, size: NSZeroSize);
imageViewObject.image = img
self.window.contentView?.addSubview(imageViewObject)

However, no image is displayed when I run this. On the debugger, I can see that imageViewObject.image (i.e. img) has a valid image, and I can view it using the eye icon.

What am I missing?


Solution

  • You are creating an image view with a zero frame, first create the image and then the view passing the proper size.

    let img = NSImage(cgImage: winCGImage, size: NSZeroSize)
    let imageViewObject = NSImageView(frame: NSRect(origin: .zero, size: img.size))
    imageViewObject.image = img
    

    Avoid to create views with the default initializer ().