无法使用文件路径设置NSImageView的图像 [英] Unable to set Image of NSImageView using file path

查看:171
本文介绍了无法使用文件路径设置NSImageView的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经迷上了NSTableView的Selection更改事件.我需要在imageview中显示选定的图像

I have hooked to Selection changed event of NSTableView.I need to display the selected image in the imageview

func tableViewSelectionDidChange(_ notification: Notification)
       {
        let table = notification.object as! NSTableView

        print(fileArray[table.selectedRow].path);
        img_view.image=NSImage(named: NSImage.Name(rawValue: fileArray[table.selectedRow].path))
       }

控制台打印

/Users/myname/Downloads/435_v9_bc.jpg

但是imageview不会显示图像.

But the imageview does not display the image.

更新1:

 print(fileArray[table.selectedRow].path);
 img_view.image=NSImage(byReferencing: URL(string: fileArray[table.selectedRow].path)!)

线程1:致命错误:在展开一个可选值时意外发现nil

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

控制台仍可打印

/Users/myname/Downloads/123_1 (1).jpeg

推荐答案

URL(string:是错误的API,对于文件系统路径,您必须使用URL(fileURLWithPath.

URL(string: is the wrong API, for file system paths you have to use URL(fileURLWithPath.

img_view.image = NSImage(byReferencing: URL(fileURLWithPath: fileArray[table.selectedRow].path))


但是fileArray[table.selectedRow]似乎已经是一个URL,因此还有一种更简便的方法


However fileArray[table.selectedRow] seems to be already an URL so there is a still easier way

img_view.image = NSImage(contentsOf: fileArray[table.selectedRow])

这篇关于无法使用文件路径设置NSImageView的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆