【发布时间】:2018-11-09 12:53:47
【问题描述】:
我在每个单元格内都有一个带有 ImageViews 的 TableView。我希望图像被加载一次并保持这种状态,但似乎图像在进入用户可见区域时被加载(下载,我从外部 API 获取它们)。这似乎是一个延迟加载或类似的东西,我想禁用它,因为如果我向下滚动然后再回来,大多数图像都会放错位置。
TableViewController.swift
cell?.mainChampImageView.image = businessLayer.getChampionThumbnailImage(championId: mainChampion.key)
BusinessLayer.swift
func getChampionThumbnailImage (championId: Int) -> UIImage {
return dataLayerRiot.getChampionThumbnailImage(championId: championId)
}
DataLayerRiot.swift
func getChampionThumbnailImage (championId: Int) -> UIImage {
var image: UIImage!
let urlString = ApiHelper.getChampionThumbnailImageApiLink(championId: championId)
let url = URL(string: urlString)
let session = URLSession.shared
let semaphore = DispatchSemaphore(value: 0)
session.dataTask(with: url!) {(data, response, error) in
if error != nil {
print("ERROR")
semaphore.signal()
}
else {
image = UIImage(data: data!)!
semaphore.signal()
}
}.resume()
semaphore.wait()
session.finishTasksAndInvalidate()
return image
}
任何人都知道如何在它们进入用户可见区域时禁用它们的加载并将它们“存储”?
编辑
我正在使用默认方式将单元格出列
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Match", for: indexPath) as? TableViewCell
...
}
有没有更好的方法?
编辑 2
我还需要说明我无法安装库,因为这是一个大学项目,我只能在大学的 MAC 上工作(因为我没有自己的 MAC),因此我无法在没有管理员权限的情况下安装包.
【问题讨论】:
-
您是否使用
dequeueReusableCell,如果是,则可能是导致问题的原因。您可能需要下载图像并缓存它们,必要时拉回正确的图像,也许这会有所帮助stackoverflow.com/a/50443730/285190 -
看看 KingFisher [github.com/onevcat/Kingfisher].它的主要目的是下载和缓存图像。
-
@Flexicoder 我添加了将单元格出列的方式,如果有更好的方法,请告诉我。另外,Alan Sarraf,我无法安装库/包,因为我没有管理员权限。
-
@CristianG 你可能需要实现
prepareForReuse()developer.apple.com/documentation/uikit/uitableviewcell/… -
@CristianG 很高兴它有帮助
标签: ios swift uitableview