swift - UICollectionView 未使用自定义 UIViewController 更新

标签 swift uicollectionview uicollectionviewcell ios9.3

我创建了一个自定义 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/

相关文章:

ios - 如何从 UICollectionViewCell 呈现一个 AlertView

ios - HTTP 加载失败(错误代码 : -999 [1:89]) for Task in iOS 11

iphone - 在 UICollectionView 中创建被子布局

ios - 将数据从一个 Collection View 传递到嵌入式 Collection View

ios - 在被点击的单元格的索引处更改数据源

ios - 如何将所选 Collection View Cell 的图像推送到另一个 View Controller?

ios - CellForRowAtIndexPath 被意外调用

ios - 如何在不重叠 TableView 中的其他单元格的情况下重用 TableView 单元格 ios swift

Swift - 为循环获取多个一对多值 - 转换为不相关的类型

ios - 在选择时为 UICollectionView 单元格设置动画