如何使用单元格中的按钮删除集合视图中的项目?
How do I delete an item in a collection view with a button in the cell?
看起来应该很容易做到,但是如何在点击单元格中的“X”按钮时删除 indexPath 中的项目?
我是否在 Cell class 中创建 IBAction?如果是这样,我如何传递 indexPath.item?
在我所做的一些研究中,我看到人们使用通知和观察者,但它似乎过于复杂。
有人可以提供使用删除按钮删除 indexPath 中的单元格的基本解决方案吗?
我正在使用 Realm 来保存项目,但我不知道在哪里放置 try! realm.write
和 realm.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)")
}
}
}
看起来应该很容易做到,但是如何在点击单元格中的“X”按钮时删除 indexPath 中的项目?
我是否在 Cell class 中创建 IBAction?如果是这样,我如何传递 indexPath.item?
在我所做的一些研究中,我看到人们使用通知和观察者,但它似乎过于复杂。
有人可以提供使用删除按钮删除 indexPath 中的单元格的基本解决方案吗?
我正在使用 Realm 来保存项目,但我不知道在哪里放置 try! realm.write
和 realm.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)")
}
}
}