【发布时间】: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