无法使用文件路径设置NSImageView的图像

问题描述 投票:0回答:1

我已经迷上了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
swift macos cocoa storyboard nsimage
1个回答
1
投票

[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])
© www.soinside.com 2019 - 2024. All rights reserved.