Unable to set Image of NSImageView using file path

浪子不回头ぞ 提交于 2020-04-17 17:55:26

问题


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))
       }

The console prints

/Users/myname/Downloads/435_v9_bc.jpg

But the imageview does not display the image.

Update 1:

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

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

Console still prints

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

回答1:


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))

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])


来源:https://stackoverflow.com/questions/61265451/unable-to-set-image-of-nsimageview-using-file-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!