首页 > 解决方案 > 为什么在 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)
        }
    }
}

标签: iosswiftuicollectionviewuicollectionviewcellnsindexpath

解决方案


阅读有关tableViewcollectionView的重用单元格

示例:在中添加代码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
}

推荐阅读