gpt4 book ai didi

Swift UIImage Named 在 UITableViewController 中为零

转载 作者:行者123 更新时间:2023-11-30 10:38:48 26 4
gpt4 key购买 nike

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

 //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:) 返回一个 URL 数组,因此当您说 for item in content 时,每个 item code> 您的一张图片的 URL。所以你可以直接加载一个item。调用 Data(contentsOf:item) 获取文件数据,并使用 UIImage(data:) 将其转换为图像。

关于Swift UIImage Named 在 UITableViewController 中为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57300985/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com