我正在加载从公共CloudKit数据库作为CKAssets获取的图像的表视图。但是,在将正确的图像加载到自定义的UIImageView单元格的UITableview之前,图像正在按顺序加载大约两秒钟。我知道问题是,由于单元格是可重用的,在用户在图像视图中显示正确的图像之前,用户正在滚动TableView时,图像仍然从CloudKit下载并显示在任何可见单元格中。我想知道这是否有一个快速修复,这样下载的图像只用于可见的单元而不是以前的任何单元格。
下面是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
}提前感谢!
发布于 2016-04-23 16:39:58
表视图出现时和调用fetchRecordsImageOperation.perRecordCompletionBlock之间存在延迟。在这段时间内,用户可能会滚动表视图,导致表视图单元格使用不同的indexPath和与其关联的不同数据去队列和请求,如果不检查单元格的索引路径是否与构建fetchRecordsImageOperation.perRecordCompletionBlock时相同,则此行:cell.photoImage.image = UIImage(data: NSData(contentsOfURL: imageAsset.fileURL)!)将导致图像放置在已经显示不同数据的单元格中。您可以像这样修改完成块以避免这种情况。
if let imageRecord = record {
NSOperationQueue.mainQueue().addOperationWithBlock() {
if let imageAsset = imageRecord.objectForKey("photoImage") as? CKAsset{
if indexPath == tableView.indexPathForCell(cell){
cell.photoImage.image = UIImage(data: NSData(contentsOfURL: imageAsset.fileURL)!)
}
self.imageCache.setObject(imageAsset.fileURL, forKey:self.photoRecord.recordID)
cell.userInteractionEnabled = true
}
}
}发布于 2016-04-24 17:04:29
你在这里找到答案,我相信,我的偏见当然是因为我写的。
How to determine when all images have been downloaded from a set in Swift?
您应该在加载图像时设置要显示的图像并显示出来,以便用户了解正在发生的事情?
https://stackoverflow.com/questions/36813061
复制相似问题