PjotrC PjotrC - 8 months ago 53
Swift Question

Swift: How to programmatically load a picture into a window?

I tried it with following code:

@IBOutlet weak var window: NSWindow!! //I don't understand this line

let imageView = NSImageView()
imageView.image = NSImage(byReferencingURL: IMAGE)

I have no compile and run time errors and the NSImage seems to have loaded the picture correctly. - But unfortunatelly it does not show up in my window.

The frame property hat to be set. Following code centers the picture in the window:

let imageView = NSImageView()
let image = NSImage(byReferencingURL: IMAGE_URL)
imageView.image = image
imageView.frame = self.window.contentView!.bounds
imageView.autoresizingMask = [.ViewWidthSizable, .ViewHeightSizable]


To programmatically add an image view to your window you will want to use an NSImageView object and set the image property. Below I've created a simple function that you can place in you window's View Controller. In addition, you should set other NSImageView properties (e.g. frame) to achieve the desired result.

func loadImageView() {
    /* Create an image view */
    let imageView = NSImageView()
    /* Set image property and replace name with your image file's name */
    imageView.image = NSImage(named: "YOUR_IMAGE_FILE_NAME_HERE")

    /* Add the new imageView to the main view */