【问题标题】:how to reload UIcollectionView data properly?如何正确重新加载 UIcollectionView 数据?
【发布时间】:2019-04-02 07:32:58
【问题描述】:

我的collectionView 单元格中的标签和 imageView 有一个默认的 UIImage 数组和名称数组。 UIcollectionviews 在我调用 reloadData() 函数并更改标签和图像视图的默认来源后,UIcollectionviews 数据不会改变,除非我将每个单元格滚动出屏幕并向后滚动以查看数据已更改。

@IBOutlet weak var mycollectionview: UICollectionView!

var castNames = ["", "", "", "", ""]

var collectionviewimages = [UIImage(named: "pic"), UIImage(named: "pic"), UIImage(named: "pic"), UIImage(named: "pic"), UIImage(named: "pic")]

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return castNames.count

    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: 
    "customcell", for: indexPath) as! MyCollectionViewCell

    cell.Initialize(image: collectionviewimages[indexPath.row]!, name: 
    castNames[indexPath.row])

    return cell
    }
}

通过点击一个按钮,我会返回一些 Json 并对其进行解析以更改 collectionView 的默认数据源。在改变了我想要的方式之后,我称之为 func:

mycollectionview.reloadData()

【问题讨论】:

  • 提供更多代码。特别是您在哪里解析数据并调用mycollectionview.reloadData()
  • 您可能在后台线程中调用reloadData
  • @TomasJablonskis 在调用 reloadData() 之前,我确信我的新数据。我打印了新数组并得到了我期望的结果。我的问题在于新数据的显示方式。
  • 单元格上的标签仅在其出列并滚动出屏幕时才会更改
  • 你设置collectionview数据源和delegate = self

标签: ios swift uicollectionview


【解决方案1】:

始终在主线程上使用 reload Collectionview。

dispatchQueue.main.async {
   self.mycollectionview.reloadData()
}

【讨论】:

    【解决方案2】:

    尝试添加这个:

    collectionView.delegate = self

    collectionView.datasource = self

    【讨论】:

    • 已经完成了。我相信如果没有这些 2,collectionview 将无法加载。
    猜你喜欢
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    相关资源
    最近更新 更多