How do I delete an item in a collection view with a button in the cell?

痴心易碎 提交于 2021-01-01 09:40:10

问题


It seems like it should be easy to do, but how do I delete the item at the indexPath when the "X" button in the cell is tapped?

Do I create an IBAction in the Cell class? If so, how do I pass in the indexPath.item?

In some research I have done, I've seen people use notifications and observers, but it seems to be overcomplicated.

Can someone provide a basic solution for deleting a cell at the indexPath with a delete button?

I am using Realm to persist the items, but I'm having trouble knowing where to put the try! realm.write and realm.delete(category) code.

Thank you.


回答1:


Closures aren't overcomplicated. Try something like this:

/// the cell
class CollectionCell: UICollectionViewCell {
    var deleteThisCell: (() -> Void)?
    @IBAction func deletePressed(_ sender: Any) {
       deleteThisCell?()
    }
}
/// the view controller

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "yourReuseID", for: indexPath) as! CollectionCell
        cell.deleteThisCell = { [weak self] in
                
        /// your deletion code here
        /// for example:

        self?.yourDataSource.remove(at: indexPath.item)
        
        do {
            try self?.realm.write {
                self?.realm.delete(projects[indexPath.item]) /// or whatever realm array you have
            }
            self?.collectionView.performBatchUpdates({
                self?.collectionView.deleteItems(at: [indexPath])
            }, completion: nil)
        } catch {
            print("Error deleting project from realm: \(error)")
        }
    }
}


来源:https://stackoverflow.com/questions/64508648/how-do-i-delete-an-item-in-a-collection-view-with-a-button-in-the-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!