【发布时间】:2017-12-19 15:25:55
【问题描述】:
我有一个collectionView。每个单元格都包含按钮 actionButton 以删除它们。按钮有removeItem 方法通过附加的目标删除它们。我有一个数组 datas 包含要收集的项目。
override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
super.collectionView(collectionView, willDisplay: cell, forItemAt: indexPath)
guard let cell = cell as? ViewCell else { return }
let index = indexPath.row % datas.count
let item = datas[index]
cell.item = item
cell.actionButton.tag = indexPath.item
cell.actionButton.addTarget(self, action: #selector(removeItem), for: .touchUpInside)
}
我有一种方法可以从集合视图中删除项目。
@objc func removeItem(sender: UIButton) {
let indexPath = IndexPath.init(item: sender.tag, section: 0)
self.datas.remove(at: indexPath.item)
collectionView?.deleteItems(at: [indexPath])
}
但在从集合单元格按钮索引中删除项目后未重新加载。例如,如果我删除索引为 [0, 0] 的第一个项目,下一个(第二个)项目变为第一个,但它的按钮索引仍然 [0, 1]。
我做错了什么以及为什么按钮索引不重新排列?
【问题讨论】:
-
也许您也应该重新加载您的收藏视图?
-
我尝试在
collectionView?.deleteItems(at: [indexPath])之后添加collectionView.reloadData(),但没有帮助。 -
无关,但为什么你的
collectionView是可选的? -
@AlexWoe89 不,不要重新加载集合视图。仅仅删除一项就太过分了。
-
@rmaddy 不幸的是,我没有找到比
self.datas.remove(at: indexPath.item)和collectionView.reloadData()更优雅的解决方案。目前,它是唯一有效的解决方案。我还在努力。
标签: swift uicollectionview uicollectionviewcell