我创建了一个自定义 UIViewController 并将其扩展为实现:UICollectionViewDataSource、UICollectionViewDelegate。在故事板中,我添加了 UICollectionView 并从我的控制器中引用了这个 UICollectionView(并为数据源和集合视图委托设置了委托)。
我显然实现了这 2 个代表的最低要求。现在,因为我有时会异步加载图像,所以我在图像下载完成后调用 cell.setNeedsLayout()、cell.layoutIfNeeded()、cell.setNeedsDisplay() 方法(cell.imageView.image = UIImage(...))。我知道所有这些方法都被调用了。但是,屏幕上的图像没有更新。
我错过了什么?谢谢!
编辑:添加示例代码 - 如何调用更新 -
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
....
let cellImage = ServiceFacade.sharedInstance.getImageFromCaching(image!.url)
if cellImage == nil {
// set image to default image.
cell.cellImage.image = UIImage(named: "dummy")
ServiceFacade.sharedInstance.getImage(image!.url, completion: { (dImage, dError) in
if dError != nil {
...
}
else if dImage != nil {
dispatch_async(dispatch_get_main_queue(),{
let thisCell = self.collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
thisCell.cellImage.image = dImage
thisCell.setNeedsLayout()
thisCell.setNeedsDisplay()
thisCell.layoutIfNeeded()
})
}
else{
// do nothing
}
})
}
else {
cell.cellImage.image = cellImage!
cell.setNeedsDisplay()
}
// Configure the cell
return cell
}