ios - 显示系统图像(SF 符号)是否使用 Swift 中的网络调用?
问题描述
我正在 ios 中创建一个应用程序,我使用 UITableView 和 UITableViewCell 从 api 加载图像。
由于 UITableView 重用单元格,所以当我快速滚动时会出现旧图像。为了防止这种情况,我使用系统图像(SF 符号)设置了默认图像。
我还使用缓存来存储图片的网址。
一切正常,但现在我想到了,我每次都发送一个网络请求来检索那个 systemImage,这似乎非常低效,因为我首先使用缓存来减少网络调用的总数。
有没有办法解决这个问题,或者这是我必须做出的权衡?
代码如下。
//use default image from SF symbols
let defaulticon = UIImage(systemName: "photo")?.withTintColor(.gray, renderingMode: .alwaysOriginal)
DispatchQueue.main.async {
cell.mealImage.image = defaulticon
}
guard cell.meal?.strMealThumb != nil else {
print("Category Image doesn't exist")
return
}
//use cache
if let imageData = model.imagecache.object(forKey: cell.meal!.strMealThumb as NSString) {
print("using cache")
DispatchQueue.main.async {
cell.mealImage.image = imageData
}
}
else {
let url = URL(string: cell.meal!.strMealThumb)
let session = URLSession.shared.dataTask(with: url!) { data, response, error in
if error == nil && data != nil {
let image = UIImage(data: data!)
//self.model.imagecache[cell.meal!.strMealThumb] = image
self.model.imagecache.setObject(image!, forKey: cell.meal!.strMealThumb as NSString)
DispatchQueue.main.async {
cell.mealImage.image = image
}
}
}
session.resume()
}
}
解决方案
覆盖prepareForReuse
方法UITableViewCell
并在此函数中添加代码以清除可能因先前使用单元格而持续存在的单相数据。在您的示例中,在此函数中分配默认图像以产生更好的结果。
推荐阅读
- google-app-engine - 如何从谷歌应用引擎(云托管)隐藏 URL 中的 .html 扩展名
- animation - ImageMagick 的转换命令可以用来创建动画 png 文件吗?
- python - 使用 python API 在大型数据库中获取结果的最快方法 - Elasticsearch
- angular - 使用 OPTIONS 方法未使用 http 请求 Angular 6 发送授权标头
- c++ - 使用模板化结构范围内的声明进行模板化
- python - 在 sympy 表达式中查找函数
- scala - 具有保留类型的序列的任何一个的通用序列
- java - 当它说类没有接受 String[] 的静态 void 主方法时在哪里添加主方法
- browser - 浏览器是否刷新服务器上的网站 DNS 缓存无响应?
- android - TelephonyManager 连接到数据网络