Nick Goldman Nick Goldman - 5 months ago 32
Swift Question

Programmatically creating a NSImageView in Swift 3.0

According to the documentation here:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSImageView_Class/

I have tried programmatically creating a NSImage view:

var thing = NSImageView.init(frame:CGRectMake(10, 10, 256, 256))

thing.image = NSImage(named:"test.png")


It runs without any errors in Xcode and successfully creates the view, but nothing can be seen in the view controller anywhere.

I also want to add the following parameters to the view but Xcode cannot find them:

thing.editable:"YES"

thing.animates:"YES"

Answer

Because you haven't added it to the window yet.

If you use storyboard:

self.view.addSubview(thing)

If you use the traditional XIB:

self.window.contentView?.addSubview(thing)

Also, you got the names of the two properties wrong. They should be:

thing.isEditable = true
thing.animates = true