Collectionview Reloaddata 函数不工作

Collectionview Reloaddata function not working

我有一个 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 [=11=].tag == 22 {
     [=11=].removeFromSuperview()
  }
}
let button = SelectionsItem(title: name, frame: createMockupButtonToGetFrame(name: name))
button.tag = 22
cell.contentView.addSubview(button)

也别忘了

button.translatesAutoresizingMaskIntoConstraints = false