【发布时间】:2021-08-30 19:21:55
【问题描述】:
我已成功从我的 collectionView 和数据源中删除项目,但在删除后没有调用 cellForItemAt,因此我的索引变得混乱。即使我在删除后立即手动调用collectionView.reloadData(),它也不起作用。
但是,如果我在collectionView.deleteItems(at: [indexPath]) 之前的任何时间调用collectionView.reloadData(),它就会被调用,但显然对我没有任何好处。不知道我做错了什么,请看一下:
class ChipView: UIView {
var chips: [ChipModel]?
lazy var collectionView: UICollectionView = {
let flowLayout = LeftAlignedCollectionViewFlowLayout()
flowLayout.scrollDirection = .vertical
let result = UICollectionView(frame: frame, collectionViewLayout: flowLayout)
result.translatesAutoresizingMaskIntoConstraints = false
result.register(Chip.self, forCellWithReuseIdentifier: "Cell")
result.delegate = self
result.dataSource = self
result.backgroundColor = .clear
result.isAccessibilityElement = false
return result
}()
func deleteItem(_ sender: Chip) {
guard let chipsArray = chips, !chipsArray.isEmpty, let indexPath = sender.indexPath else { return }
// 1. remove value from source of truth
chips?.remove(at: indexPath.row)
// 2. delete item from collection view
collectionView.deleteItems(at: [indexPath])
// TODO: - Figure out why cellForItemAt isn't getting called after collectionView.deleteItems... Needs to update the indexPath
collectionView.reloadData()
}
extension ChipView: UICollectionViewDataSource {
public func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
return chips?.count ?? 0
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Chip
cell.indexPath = indexPath
if let chip = chips?[indexPath.row] {
cell.setupChip(title: chip.title, icon: chip.icon, chipState: chip.chipState)
}
return cell
}
}
【问题讨论】:
-
您的错误是将索引路径分配给单元格。不要那样做。
标签: ios swift uicollectionview reloaddata