【问题标题】:How do I delete an item in a collection view with a button in the cell?如何使用单元格中的按钮删除集合视图中的项目?
【发布时间】:2020-10-23 23:55:30
【问题描述】:

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

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

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

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

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

谢谢。

【问题讨论】:

    标签: swift realm uicollectionviewcell


    【解决方案1】:

    闭包并不过分复杂。试试这样的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多