繁体   English   中英

UICollectionView重新加载数据不会更新单元格

[英]UICollectionView reload data doesn't update cells

我想通过说我已经习惯了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
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM