swift - Collectionview Reloaddata 函数不工作

标签 swift uicollectionview reloaddata

我有一个 collectionView,我在其中显示带有 UIButton 的普通 UICollectionViewCell。在另一个屏幕上,我有一个开关列表。每当这些更改时,就会使用 collectionView 将更新发送到屏幕。当我关闭一个开关(并且更新了数据源)时,我尝试使用 reloadData 函数重新填充 collectionView。但是,按钮(单元格)显示在彼此之上。

我尝试使用 reloadData,在 Dispatch.main.async 中执行它,使 collectionView 无效,删除 deleteSections 函数并访问特定单元格并使用 cell.removeFromSuperView() 将其删除。

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath)
        let name = PickingState.getSelectedFilterValues()[indexPath.row]
        let button = SelectionsItem(title: name, frame: createMockupButtonToGetFrame(name: name))

        print(name)

        cell.contentView.addSubview(button)
        cell.contentView.addConstraintsWithFormat(formatString: "H:|[v0]|", views: button)
        cell.contentView.addConstraintsWithFormat(formatString: "V:|[v0]|", views: button)

        return cell
    }

期望单元格重新渲染而不是彼此重叠。

最佳答案

问题就在这里

cell.contentView.addSubview(button)

由于单元格出列,您需要在添加之前清除所有按钮

cell.contentView.forEach { 
  if $0.tag == 22 {
     $0.removeFromSuperview()
  }
}
let button = SelectionsItem(title: name, frame: createMockupButtonToGetFrame(name: name))
button.tag = 22
cell.contentView.addSubview(button)

也别忘了

button.translatesAutoresizingMaskIntoConstraints = false

关于swift - Collectionview Reloaddata 函数不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56890053/

相关文章:

ios - 当设备旋转时如何在不将设备锁定为纵向模式的情况下将 collectionView 的所有项目固定到位?

ios - UIGesture LongPress 复制单元格

php - 使用 NSURLSession 将带符号 (&) 的字符串从 iOS 传递到 PHP/MySQL

ios - UICollectionViewCell cellSize 不适用于最后一项

ios - 如何自定义 UICollectionView Cell 以显示如附件所示的图像网格?

iphone - 如何沿滚动动态加载带有项目的 iOS iCarousel

ios - 在 numberOfItemsInSection 返回非零项目编号后未调用 UICollectionView cellForItemAtIndexPath

ios - 在 GCD 主要威胁中频繁调用 "tableView.reloadData"得到崩溃错误 "Index out of range"

xcode - 对数组中的字典进行排序

ios - 两个不同层上的两个 CABasicAnimation 同时进行