Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

swift - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...