BriScoLeg
BriScoLeg

Reputation: 105

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

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.

Upvotes: 0

Views: 1541

Answers (1)

aheze
aheze

Reputation: 30308

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)")
        }
    }
}

Upvotes: 2

Related Questions