我正在加载从公共 CloudKit 数据库作为 CKAssets 获取的图像的表格视图。但是,在将正确的图像加载到自定义 UITableview 单元格的 UIImageView 之前,图像会乱序加载大约两秒钟。我知道问题在于,由于单元格是可重复使用的,因此图像仍然从 CloudKit 下载并显示在任何可见的单元格中,而用户在正确的图像显示在图像视图中之前滚动 TableView 时。我想知道是否有快速解决此问题的方法,以便下载的图像仅适用于可见单元格的图像,而不适用于任何以前的单元格。
这是 cellForRowAtIndexPath 的代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! PostsTableViewCell
cell.userInteractionEnabled = false
photoRecord = sharedRecords.fetchedRecords[indexPath.row]
cell.photoTitle.text = photoRecord.objectForKey("photoTitle") as? String
cell.photoImage.backgroundColor = UIColor.blackColor()
cell.photoImage.image = UIImage(named: "stock_image.png")
if let imageFileURL = imageCache.objectForKey(self.photoRecord.recordID) as? NSURL {
cell.photoImage.image = UIImage(data: NSData(contentsOfURL: imageFileURL)!)
cell.userInteractionEnabled = true
print("Image Cached: \(indexPath.row)")
} else {
let container = CKContainer.defaultContainer()
let publicDatabase = container.publicCloudDatabase
let fetchRecordsImageOperation = CKFetchRecordsOperation(recordIDs:[self.photoRecord.recordID])
fetchRecordsImageOperation.desiredKeys = ["photoImage"]
fetchRecordsImageOperation.queuePriority = .VeryHigh
fetchRecordsImageOperation.perRecordCompletionBlock = {(record:CKRecord?, recordID:CKRecordID?, error:NSError?) -> Void in
if let imageRecord = record {
NSOperationQueue.mainQueue().addOperationWithBlock() {
if let imageAsset = imageRecord.objectForKey("photoImage") as? CKAsset{
cell.photoImage.image = UIImage(data: NSData(contentsOfURL: imageAsset.fileURL)!)
self.imageCache.setObject(imageAsset.fileURL, forKey:self.photoRecord.recordID)
cell.userInteractionEnabled = true
}
}
}
}
publicDatabase.addOperation(fetchRecordsImageOperation)
}
return cell
}
提前致谢!