我在每个单元格内都有一个带有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上工作(因为我不拥有它),因此我无法在没有管理员特权的情况下安装软件包。
最佳答案
您应该将任务保存在内存中,例如:
let task = = session.dataTask() {}
在您可以通过以下任何方式取消它之后:
task.cancel()
或者,如果对象 session 是
URLSession
实例,则可以通过以下方式取消它:session.invalidateAndCancel()
关于ios - 当进入 View 时如何禁用TableView单元格图像下载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53226081/