Swift UIImage Named 在 UITableViewController 中为 nil

Swift UIImage Named is nil inside UITableViewController

我正在尝试将其他图像添加到我的 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
            }
        }
    }

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

但是,解决方法很简单:不要使用 UIImage(named:)。也不要使用路径名。完全没有必要。你手头有解决方案:contentsOfDirectory(at:) returns 一个 URL 的数组,所以当你说 for item in contents 时,每个 item 是您其中一张图片的 URL。所以你可以直接加载一个 item 。调用 Data(contentsOf:item) 获取文件数据,并使用 UIImage(data:).

将其转换为图像