我具有以下功能:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)
{
if editingStyle == .delete
{
myItemsInCart.remove(at: indexPath.row)
tableView.reloadData()
}
}
@objc func removeTapped(tapGestureRecognizer: UITapGestureRecognizer){
let removeImage = tapGestureRecognizer.view as! UIImageView
print("my taped image view tag is : \(removeImage .tag)")
}
默认情况下,我可以向左滑动来删除行:
但是我想通过单击“删除”图标而不是滑动来删除单元格。
答案 0 :(得分:1)
您可以创建一个协议来完成此操作。这只是多种方法之一。
代码:
class MyTableViewController: ItemCellDelegate {
func deleteCell(cell: ItemCell) {
let indexPath = tableView.indexPath(for: cell)
myItemsInCart.remove(at: indexPath.row)
tableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ItemCell
cell.delegate = self
return cell
}
}
protocol ItemCellDelegate {
var delegate: UIViewController? { get set }
func deleteCell(cell: ItemCell)
}
class ItemCell: UITableViewCell {
var indexPath: IndexPath?
var delegate: ItemCellDelegate?
@objc func deleteCell(_ sender: Any?) {
delegate?.deleteCell(cell: self)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
deleteButton.addTarget(self, action: #selector(deleteCell), for: .touchUpInside)
}
}