【问题标题】:Swift UIImage Named is nil inside UITableViewControllerSwift UIImage Named 在 UITableViewController 中是 nil
【发布时间】:2019-08-01 02:08:47
【问题描述】:

我正在尝试将其他图像添加到我的 UITableViewController 中,并且我创建了一个从包含渲染所需的所有图像的包中读取的函数。问题是某些图像作为 UIImage 工作,而其他图像在创建 UIImage 对象时返回 nil。我不确定导致此问题的原因是什么,因为图像位于捆绑包内并且可以预览它。谢谢!

 //Retrieve Icons
 //Read from file path and append it to an array.


 //Retrieve Icons
    //Read from file path and append it to an array.
    private func loadIcons() {
        let fileManager = FileManager.default
        let bundleURL = Bundle.main.bundleURL
        let assetURL = bundleURL.appendingPathComponent("UIAssets.bundle")
        let contents = try! fileManager.contentsOfDirectory(at: assetURL, includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey], options: .skipsHiddenFiles)

        //BUG: doesnt work with some png/jpg image is returning nil
        for item in contents {
            let itemStr = item.absoluteString
            if itemStr.contains("png") || itemStr.contains("jpg"){
                let imageName = (itemStr as NSString).lastPathComponent
                print(imageName)
                let image = UIImage(named: imageName)
                self.models[imageName] = image
            }
        }
    }

【问题讨论】:

  • 打印这一行 let itemStr = item.absoluteString
  • 使用 URL 而不是字符串。
  • 另外,如果您有图像文件的 URL,则不需要其名称。整个转换是没有意义和不必要的。直接加载数据即可。这也快得多。

标签: swift xcode image null uiimage


【解决方案1】:

我很惊讶这对任何图像都有效,因为UIImage(named:) 不适用于主包子目录中的图像。它只查看主包的顶层。

不过,解决方法很简单:不要使用UIImage(named:)。也不要使用路径名。完全没有必要这样做。您已经有了解决方案:contentsOfDirectory(at:) 返回一个 URL 数组,所以当您说 for item in contents 时,每个 item 都是您的一张图片的 URL。所以你可以直接加载item。调用Data(contentsOf:item)获取文件数据,并使用UIImage(data:)将其转换为图像。

【讨论】:

  • 非常感谢您的澄清!这有助于解决我遇到的问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-13
  • 2016-12-04
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多