无法使用 NSImage(byReferencingFile:) 从文件加载 NSImageView 图像

Can not load NSImageView image from file with NSImage(byReferencingFile: )

当我想将我的光盘 (/Users/me/Desktop/image.png) 中的图像设置为 NSImageViewNSImage(byReferencingFile: ) 的图像时它没有显示它。

当我尝试 NSImage(named: ) 使用存储在 assets-folder 中的图像时,它起作用了。

内码viewController

class ViewController: NSViewController {
    @IBOutlet var imageView: NSImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        imageView.image = NSImage(byReferencingFile: "/Users/me/Desktop/image.png")
    }    
}

imageView填满整个window。

所以我想加载存储在磁盘上或指定位置的图像URL。

您不能将桌面上的图像添加到 UIimageView,只能将图像添加(拖动)到项目文件夹中,然后 select 将名称图像添加到 UIimageView 属性(检查器)中。

要访问 UserDir,您必须使用:

let home = FileManager.default.homeDirectoryForCurrentUser

然后您可以从那里添加图像的路径 这是有关使用文件系统的教程 https://www.raywenderlich.com/666-filemanager-class-tutorial-for-macos-getting-started-with-the-file-system

希望对您有所帮助。

Willeke 帮助我找到了解决方案。我不得不将 entitlements-file 中的 App SandboxYES 切换到 NO