我创建了一个自定义 UIViewController 并将其扩展以实现:UICollectionViewDataSource、UICollectionViewDelegate。在 Storyboard中,我添加了 UICollectionView 并从我的 Controller 对此 UICollectionView 进行引用(并设置数据源和 Collection View 委托(delegate)的委托(delegate))。
我显然实现了这两名代表的最低要求。现在,由于我有时会异步加载图像,因此我在图像下载完成后调用 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
}
最佳答案
UICollectionView
可能已缓存单元格的中间表示,以便它可以快速滚动。
您应该调用的例程是 reloadItemsAtIndexPaths
,以指示您的单元格需要更新、调整大小并重做其视觉表示,其中包含代表您的单元格的单个索引路径。
关于swift - UICollectionView 未使用自定义 UIViewController 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36296841/