【问题标题】:UICollectionView Not Updated with custom UIViewControllerUICollectionView 未使用自定义 UIViewController 更新
【发布时间】:2016-03-29 23:19:36
【问题描述】:

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

}

【问题讨论】:

  • 你是在主线程下载后设置图片吗?下载完成后,单元格可能为 nil。如果可以在下载设置图片的时候贴出一些代码
  • Yan,感谢您帮我调查。这是我用来调用单元格更新的代码。但它没有用。

标签: swift uicollectionview uicollectionviewcell ios9.3


【解决方案1】:

UICollectionView 可能已经缓存了您单元格的中间表示,以便它可以快速滚动。

您应该调用的例程来指示您的单元格需要更新、调整大小并重做它的视觉表示是reloadItemsAtIndexPaths,其中一个索引路径代表您的单元格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    相关资源
    最近更新 更多