【问题标题】:My code NSimage( ) works fine in Swift 3 but it does not work in Swift 5我的代码 NSimage() 在 Swift 3 中运行良好,但在 Swift 5 中无法运行
【发布时间】:2019-04-23 23:46:20
【问题描述】:

我的代码是在窗口中显示 image.jpg。那是用 Swift 3 编写的。最近,我用 Xcode 10.2 更新到 Swift 4。它根本不起作用。我还在 Swift 5 中重写了它。它仍然不起作用。我必须下载旧的 Xcode 10 才能在 Swift 3 中运行我的代码才能再次工作。我想知道代码发生了什么。

这是我显示图片的主要代码。

override func viewDidAppear() {
    super.viewDidAppear()

    imageView.image = NSImage(byReferencingFile: "\(ViewController.GlobaVariable.selecFile)" )

    print("\(ViewController.GlobaVariable.selecFile)")
    /// The print statement work  but not the image.
}

【问题讨论】:

  • 您是否检查过NSImage(byReferencingFile: "\(ViewController.GlobaVariable.selecFile)" ) 不为零?
  • 我检查了输出为零。我该如何解决?我想知道为什么它在 swift 3 中有效,但在 swift 4 和 5 中无效?
  • 您的文件在哪里?不要保存整个文件路径。您应该只保存文件名及其位置/目录
  • 文件位于文档目录中。我只是使用 GlobaVaraible 来传输路径。它在 swift 3 中运行良好。
  • 让我们看看声明selecFile的代码。您不应该使用字符串插值将其转换为字符串。根据属性的类型,不同版本的 Swift 可能会做略微不同的插值。

标签: swift cocoa nsimage


【解决方案1】:
    let openPanel = NSOpenPanel()
    openPanel.beginSheetModal(for:self.view.window!) { (response) in
        if response.rawValue == NSFileHandlingPanelOKButton
        {
            let fileURL = openPanel.url!

            //////////////////
            let ph = fileURL.absoluteString
            let path = (ph as NSString).substring(from: 7)
            //print(path)

            //////////////////////

            GlobaVariable.selecFile = path

        }
    }

【讨论】:

  • 问答之间没有明显的联系。
猜你喜欢
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-25
  • 1970-01-01
  • 2015-01-19
相关资源
最近更新 更多