ios - 为什么在 URLSessionTask 完成后 indexPath 会发生变化?
问题描述
我正在学习 ios 编码和阅读一本书。UICollectionViewCell 的 indexPath 有一些我不明白的地方。UICollectionView 显示使用带有 URLSessionDataTask 的 Photo 对象的 remoteUrl 属性获取的图像。将转义的完成处理程序传递给图像获取函数以更新单元格内的 UIImageView。
书中代码片段的注释说“照片的索引路径可能在请求开始和完成之间发生了变化”。为什么会这样?
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let photo = photoDataSource.photos[indexPath.row]
// Download the image data, which could take some time
photoStore.fetchImage(photo: photo) { (result) in
// The index path for the photo might have changed between the
// time the request started and finished, so find the most
// recent index path
guard
let photoIndex = self.photoDataSource.photos.firstIndex(of: photo),
case let .success(image) = result
else {
return
}
let photoIndexPath = IndexPath(row: photoIndex, section: 0)
// When the request finishes, only update the cell if it's still visible
if let cell = collectionView.cellForItem(at: photoIndexPath) as? PhotoCollectionViewCell {
cell.updateImage(image: image)
}
}
}
解决方案
阅读有关tableView或collectionView的重用单元格
示例:在中添加代码viewDidLoad
:
collectionView.register(UICollectionViewCell.self, forCellReuseIdentifier: "Your Reuse Identifier")
在Extension
你的 viewController (UICollectionViewDelegateFlowLayout)
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Your Reuse Identifier", for: indexPath)
cell.imageView.image = photos[indexPath.row]
return cell
}
推荐阅读
- javascript - 巴西电话号码的正则表达式
- date - grails 3.3.x java.sql.Date 属性类型不匹配
- acumatica - 是什么导致 Acumatica 2017R2 中的 REST API 错误?
- python - Python 在分隔符上拆分字符串,但不在此类分隔符的某个变体上
- elasticsearch - 弹性搜索相关性 - 5.3
- python - Python:在熊猫中访问单元格值并执行数学运算
- python - Tkinter 在 Python 中创建 GUI 应用程序的一般问题
- c++ - Visual C++ UMDF V2 模板似乎创建了一个 C 项目,而不是 C++
- c# - 是否可以在 web.config 中不添加 maxRequestLength 的情况下流式上传大文件?
- python-3.x - Slack API:使用 chat.postMessage 时出现 channel_not_found 错误