【问题标题】:UICollectionView reload data doesn't update cellsUICollectionView 重新加载数据不会更新单元格
【发布时间】:2016-12-01 04:15:26
【问题描述】:

我想先说我已经习惯了 UITableViews 的工作方式并且对 UICollectionView 不是很熟悉。

我实际上在做的是

  1. 在屏幕上添加视图(包括集合视图)
featuredCollectionView = UICollectionView(frame: CGRect(x: 0, y: featuredLabel.frame.origin.y + featuredLabel.frame.size.height, width: view.frame.size.width, height: 216), collectionViewLayout: layout)
        featuredCollectionView.delegate = self
        featuredCollectionView.dataSource = self
        featuredCollectionView.register(ItemCollectionViewCell.self, forCellWithReuseIdentifier:
        "cell")
        featuredCollectionView.backgroundColor = UIColor.fysGray
        featuredCollectionView.showsHorizontalScrollIndicator = false
        // add view to screen 
  1. 从网络加载数据并添加到数据源数组中
func fetchPosts()
{
  // note some libs have been changed for x purposes 
  NetworkClass.loadPosts()
  { (data, error) in 
    // parse into valid object 
    // add to datasource array
    self.featuredItems.append(item)

    // reload data 
    DispatchQueue.main.async
    {
        self.featuredCollectionView.reloadData()
    }

  }
  1. collectionView.reloadData() 在主队列上,如上图所示

调用重新加载数据后,屏幕上没有任何内容,好像它是空白的。我已经尝试从主队列重新加载并插入/执行批量更新等。我只是对如何让它工作感到非常困惑。在从网络加载之前,我必须知道项目的数量吗?我怎样才能得到这个工作?

这里是 cellForItemAt 的代码

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    var item: Item
    if collectionView == featuredCollectionView
    {
        item = featuredItems[indexPath.row]
    }
    else
    {
        item = recentlyViewedItems[indexPath.row]
    }


    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ItemCollectionViewCell
    cell.item = item
    return cell
}

【问题讨论】:

  • 检查你的collectionView框架。我认为现在为零。或者你肯定会为 collectionView 设置数据源。
  • 你也可以添加一些代码吗?
  • 我设置了一个数据源,框架不为零。我会发布一些代码
  • 您的日志中有数据吗?
  • 是的,数据完全没问题。我还在`func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int`中打印项目的数量,它们不是0

标签: ios uicollectionview


【解决方案1】:

最终成为 cell 方法中的 if 条件的问题。由于某种原因它不喜欢它,所以我使用了两个单独的视图控制器和一个容器视图,它与reloadData() 一起工作就像一个魅力@

【讨论】:

    猜你喜欢
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多