【问题标题】:Unable to set Image of NSImageView using file path无法使用文件路径设置 NSImageView 的图像
【发布时间】:2020-07-30 14:10:08
【问题描述】:

我已经连接到 NSTableView 的选择更改事件。我需要在图像视图中显示选定的图像

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

【问题讨论】:

  • NSImage(byReferenceFile: "/Users/myname/Downloads/435_v9_bc.jpg")
  • @DilanAnuruddha 请查看更新

标签: swift macos cocoa storyboard nsimage


【解决方案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])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 2019-08-20
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多