我已经迷上了NSTableView的Selection更改事件。我需要在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不显示图像。
更新1:
print(fileArray[table.selectedRow].path);
img_view.image=NSImage(byReferencing: URL(string: fileArray[table.selectedRow].path)!)
线程1:致命错误:展开一个可选值时意外发现nil
控制台仍然打印
/Users/myname/Downloads/123_1 (1).jpeg
[URL(string:
是错误的API,对于文件系统路径,您必须使用URL(fileURLWithPath
。
img_view.image = NSImage(byReferencing: URL(fileURLWithPath: fileArray[table.selectedRow].path))
但是fileArray[table.selectedRow]
似乎已经是一个URL,所以还有一种更简便的方法
img_view.image = NSImage(contentsOf: fileArray[table.selectedRow])