如何在单元格中带有按钮的集合视图中删除项目?

问题描述

似乎应该很容易做到,但是当点击单元格中的“ X”按钮时,如何删除indexPath上的项目?

我是否在Cell类中创建IBAction?如果是这样,如何传递indexPath.item?

在我做过的一些研究中,我看到人们使用通知和观察者,但这似乎过于复杂了。

有人可以提供使用删除按钮删除indexPath上的单元格的基本解决方案吗?

我正在使用Realm保留项目,但是我不知道将try! realm.writerealm.delete(category)代码放在哪里。

谢谢。

解决方法

关闭并不复杂。尝试这样的事情:

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