xcode Swift:如何更改 NSImage 图像源?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26774574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:06:40  来源:igfitidea点击:

Swift: How to change NSImage image source?

xcodeswiftnsviewnsimagensimageview

提问by udondan

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.

我是 XCode 和 Swift 的新手。试图在 OS X 应用程序中简单地在我的视图中设置图像。图像应该从网络加载,但我认为这无关紧要。

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.

我创建了一个新的 Cocoa App,有一个有效的列表视图。在列表行的 XIB 中,我放置了一个“图像视图”元素,这样我就可以在每一行中显示一个静态图像。

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 @IBOutletto the code.

现在我想在行加载时更改图像 URL。我将图像中的线条拖到我的控制器类中,该类将 加到@IBOutlet代码中。

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 funnyfrustrating error message from the last statement (self.rowImage.image(image)) is

现在来自最后一条语句 ( )的非常有趣的令人沮丧的错误消息self.rowImage.image(image)

Cannot convert the expression's type 'NSImage' to type 'NSImage?'.

无法将表达式的类型“NSImage”转换为“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.

好的。这是什么意思,我该如何解决?这在某种程度上与选项有关吗?我尝试了?'s 和!'s 但就是无法弄清楚 XCode 对我的期望。

采纳答案by rintaro

imageof NSImageViewis a property, you can just assign to it.

imageofNSImageView是一个属性,你可以分配给它。

self.rowImage.image = image

And, your URL is wrong NSURL(fileURLWithPath:)is for local files. Use NSURL(string:)instead.

而且,您的 URL 是错误的NSURL(fileURLWithPath:),用于本地文件。使用NSURL(string:)来代替。

var url = NSURL(string: "http://example.com/some-image.png")