- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在加载一个图像 TableView ,这些图像是作为 CKAssets 从公共(public) CloudKit 数据库中获取的。但是,在将正确的图像加载到自定义 UITableview 单元格的 UIImageView 之前,图像会乱序加载大约两秒钟。我知道问题在于,由于单元格是可重用的,因此在 ImageView 中显示正确的图像之前,当用户在 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
}
提前致谢!
最佳答案
表格 View 出现和调用 fetchRecordsImageOperation.perRecordCompletionBlock
之间存在延迟。在那段时间内,如果您不检查单元格的索引路径是否与构造 时相同,则用户可能会滚动表格 View ,导致表格 View 单元格使用不同的 indexPath 和与之关联的不同数据进行出队和重新排队fetchRecordsImageOperation.perRecordCompletionBlock
,此行:cell.photoImage.image = UIImage(data: NSData(contentsOfURL: imageAsset.fileURL)!)
已经显示不同的数据。您可以像这样修改完成 block 以避免这种情况。
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
}
}
}
关于ios - 来自 CKAsset 的图像在 Swift 中加载乱序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36813061/
我是一名优秀的程序员,十分优秀!