问题描述
看起来应该很容易做到,但是当X"被删除时,如何删除 indexPath 处的项目.单元格中的按钮被点击?
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?
我是否在 Cell 类中创建了一个 IBAction?如果是这样,我如何传入 indexPath.item?
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.
有人可以提供使用删除按钮删除 indexPath 处的单元格的基本解决方案吗?
Can someone provide a basic solution for deleting a cell at the indexPath with a delete button?
我正在使用 Realm 来持久化这些项目,但我不知道该把 try! 放在哪里!realm.write
和 realm.delete(category)
代码.
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.
谢谢.
推荐答案
闭包并不过分复杂.尝试这样的事情:
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)")
}
}
}
这篇关于如何使用单元格中的按钮删除集合视图中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!