实际上,我为电子商务应用开发了愿望清单页面。愿望清单单元格包含一个爱(愿望清单)按钮。
class WishCell: UICollectionViewCell {
var wishButtonTapped : (() -> Void)? = nil
@IBAction func wishBtnTapped(_ sender: Any) {
if let wishBtnTap = wishButtonTapped {
wishBtnTap()
}
}
}
按钮单击在CellForRowAt中处理。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WishCell", for: indexPath) as? WishCell {
cell.configureCell(wishlist: wishlists[indexPath.row])
// Wish Button
cell.wishButtonTapped = {
print("indexPath", indexPath)
print("indexPathRow", indexPath.row, wishlistJSON.count)
// wishlistJSON.remove(at: indexPath.row)
// self.parseWishlistJSON()
self.wishlists.remove(at: indexPath.row)
collectionView.deleteItems(at: [indexPath])
// self.collectionView.reloadData()
self.updateDesign()
}
return cell
} else {
return UICollectionViewCell()
}
}
点击第三个单元格
indexPath [0, 2]
indexPathRow 2 5
再次点击第三个单元格
indexPath [0, 3]
indexPathRow 3 5
wishlistJSON.remove(at: indexPath.row)
崩溃应用程序,因为数组indexOutOfBound 答案 0 :(得分:1)
我遇到了同样的问题,对我来说,强制执行collectionView.reloadData()可以解决问题。仍然不清楚为什么删除行不会更新单元格的IndexPath ...但是至少可以使它正常工作
答案 1 :(得分:0)
When cells get reused, cell.wishButtonTapped actions will get added again! That's not what we want.
protocol WishlistDelegate: class {
func wishlistBtnTap(_ sender: WishCell)
}
class WishCell: UICollectionViewCell {
weak var delegate: WishlistDelegate?
@IBAction func wishBtnTapped(_ sender: Any) {
delegate?.wishlistBtnTap(self)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WishCell", for: indexPath) as? WishCell {
cell.configureCell(wishlist: wishlists[indexPath.row])
cell.delegate = self
return cell
} else {
return UICollectionViewCell()
}
}
extension WishlistVC: WishlistDelegate {
func wishlistBtnTap(_ sender: WishCell) {
guard let tappedIndexPath = collectionView.indexPath(for: sender) else { return }
// Delete the Item
wishlists.remove(at: tappedIndexPath.row)
collectionView.deleteItems(at: [tappedIndexPath])
}
}
答案 2 :(得分:0)
重新加载Collection-view必须要做到这一点
[self.collectionView performBatchUpdates:^{
[self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
}