我正在展示一个由RxRealmDataSources驱动的UITableView
。
当表中的行被删除时,我需要执行一些操作。
有没有办法让每当从表中删除一行时,都会使用已删除行的索引路径调用一个函数?
编辑-
我的应用程序中UITableView
单元格的 UI 取决于 2 件事 -
- 从领域数据库获取的数据对象 ( info )
- 行的索引位置
每当删除单元格时,我都需要更新其下一个单元格的 UI。
如果数据库更新的唯一方法是用户的直接操作,那么我可以使用func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)
方法来获取应删除的单元格的indexPath
并更新下一个单元格的 UI。
但是,数据库同步到云,数据库绑定到表视图,因此我无法控制何时添加或删除单元格。正是出于这个原因,我想知道是否有办法知道何时从UITableView
中删除细胞
由于UITableView
中单元格的可重用性,在表本身被解除分配之前,单元格实际上不会被删除。
我可能会假设"删除"单元格是指单元格从屏幕上消失。在这种情况下,以下UITableViewDelegate
函数可能会对您有所帮助(当单元格不再可见时调用):
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath)
在评论中你说:
通过"删除",我的意思是从表格视图中删除单元格时,就像我们向左滑动单元格以将其删除一样。
由于您标记了 RxSwift,因此解决方案是使用以下itemDeleted
:
tableView.rx.itemDeleted
.subscribe(onNext: { print("delete item at index path ($0) from your model.")})
.disposed(by: bag)
如果您不是在寻找 Rx 解决方案,那么您的问题就是以下内容:
添加滑动以删除 UITableViewCell
我能够通过子类化UITableView
类并覆盖func deleteRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation)
方法来解决这个问题。
您必须实现 UITableView 的 1 个委托方法。
- 尾随滑动操作配置为行在
它很容易实现。此委托方法将被调用两次,一次是在轻扫时调用,另一次是在按下以删除行时调用。
`enter code here`
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let config = UISwipeActionsConfiguration(actions: [makeDeleteContextualAction(forRowAt: indexPath)])
config.performsFirstActionWithFullSwipe = true
return config
}
private func makeDeleteContextualAction(forRowAt indexpath:IndexPath) -> UIContextualAction {
let deleteAction = UIContextualAction(style: .destructive, title: LocalizableConstants.constLS_global_delete()) { (action, swipeButtonView, completion) in
let product = self.products[indexpath.row]
if let quantity = product.vo_quantity(), let amount = product.vo_priceFide() {
self.totalProducts -= Int(truncating: quantity)
self.totalAmount -= amount.doubleValue * quantity.doubleValue
}
DispatchQueue.main.async {
self.lbBasketNumber.text = String(self.totalProducts)
self.lbTotalAmount.text = String(self.totalAmount)
}
self.products.remove(at: indexpath.row)
self.tableView.deleteRows(at: [indexpath], with: .fade)
if #available(iOS 13.0, *) {
action.image = ImagesConstants.constIMG_XCA_mini_icon_red_trash()
action.image?.withTintColor(ConstantsColor.const_COLOR_RED())
action.backgroundColor = ConstantsColor.const_COLOR_WHITE()
} else {
action.title = LocalizableConstants.constLS_global_delete()
}
completion(true)
}
return deleteAction
}