通过单击图像删除表行

时间:2019-07-18 15:23:34

标签: swift uitableview

我具有以下功能:

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)")

}

默认情况下,我可以向左滑动来删除行:

image

但是我想通过单击“删除”图标而不是滑动来删除单元格。

1 个答案:

答案 0 :(得分:1)

您可以创建一个协议来完成此操作。这只是多种方法之一。

  1. 使您的UITableViewController遵守协议
  2. 将indexPath和委托属性添加到您的单元格
  3. 在cellForIndexPath中,设置单元的委托和indexPath属性
  4. 在您的单元格子类中,向按钮添加一个目标,该目标在按下时将调用该单元格的委托的deleteCell函数。

代码:

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)
    }
}