在 UITableview 上滑动删除而不确认
Swipe to delete without confirmation on UITableview
我有一个 table视图,其中包含使用 websocket 的实时数据。 Table 视图每两秒刷新一次单元格(或行)。
我想实现滑动删除功能(不显示删除按钮),因为我每两秒调用一次重新加载行,尝试删除特定行 table 视图对齐折叠。有人可以帮忙吗?
您可以将 UISwipeGestureRecognizer 添加到您的 TableViewCell
中。
例如
let swipeToDeleteGesture = UISwipeGestureRecognizer(target: self, action: #selector(deleteCellWithoutConfirm(gesture:)))
swipeToDeleteGesture.direction = .left
your_cell.addGestureRecognizer(swipeToDeleteGesture)
并处理删除函数
@objc func deleteCellWithoutConfirm(gesture: UIGestureRecognizer) {
guard let cell = gesture.view as? UITableViewCell,
let indexPath = tableView.indexPath(for: cell) else {
return
}
// delete your data first, then reload tableView
your_data.remove(at: indexPath.row)
tableView.reloadSections(IndexSet(integer: 0), with: UITableViewRowAnimation.fade)
}
Swift 4
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
data.remove(at: indexPath.row)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .middle)
tableView.endUpdates()
}
}
我有一个 table视图,其中包含使用 websocket 的实时数据。 Table 视图每两秒刷新一次单元格(或行)。
我想实现滑动删除功能(不显示删除按钮),因为我每两秒调用一次重新加载行,尝试删除特定行 table 视图对齐折叠。有人可以帮忙吗?
您可以将 UISwipeGestureRecognizer 添加到您的 TableViewCell
中。
例如
let swipeToDeleteGesture = UISwipeGestureRecognizer(target: self, action: #selector(deleteCellWithoutConfirm(gesture:)))
swipeToDeleteGesture.direction = .left
your_cell.addGestureRecognizer(swipeToDeleteGesture)
并处理删除函数
@objc func deleteCellWithoutConfirm(gesture: UIGestureRecognizer) {
guard let cell = gesture.view as? UITableViewCell,
let indexPath = tableView.indexPath(for: cell) else {
return
}
// delete your data first, then reload tableView
your_data.remove(at: indexPath.row)
tableView.reloadSections(IndexSet(integer: 0), with: UITableViewRowAnimation.fade)
}
Swift 4
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
data.remove(at: indexPath.row)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .middle)
tableView.endUpdates()
}
}