I'm a newbee with XCode and Swift. Trying to simply set an image in my view in an OS X application. The image should be loaded from the web, but I think that doesn't matter.
I created a new Cocoa App, have a list view which works. In the XIB for the list row I have placed an "Image View" element and with this I can display a static image in each row.
Now I want to change the image URL when the row loads. I dragged the line from the image to my controller class, which added the @IBOutlet
to the code.
This is my code of the controller class:
import Cocoa
class ListRowViewController: NSViewController {
@IBOutlet weak var rowImage: NSImageView!
override var nibName: String? {
return "ListRowViewController"
}
override func loadView() {
super.loadView()
var url = NSURL(fileURLWithPath: "http://example.com/some-image.png")
var image = NSImage(byReferencingURL: url!)
self.rowImage.image(image)
}
}
Now the very funny frustrating error message from the last statement (self.rowImage.image(image)
) is
Cannot convert the expression's type 'NSImage' to type 'NSImage?'.
OK. What does that mean and how do I fix it? Is that somehow related to optionals? I experimented with ?
's and !
's but just can't figure out what XCode expects from me.
image
of NSImageView
is a property, you can just assign to it.
self.rowImage.image = image
And, your URL is wrong NSURL(fileURLWithPath:)
is for local files. Use NSURL(string:)
instead.
var url = NSURL(string: "http://example.com/some-image.png")