Delete a row from table view using custom button -

2019-03-06 06:57发布

问题:

How to delete a row from tableview using custom buttom

//CustomCell.swift

protocol FavoriteCellDelegate {
    func deleteButton(sender:CustomCell)
}

class FavoriteItemTableViewCell: UITableViewCell{
    var delegate: FavoriteCellDelegate!
    @IBAction func deleteButton(_ sender: UIButton) {
    delegate.deleteButton(sender: self)
}
}


CustomClass:UITableViewDataSource,UITableViewDelegate,CustomCellDelegate{
@IBOutlet weak var tableView: UITableView!
// all necessary functions for table view....

// Function delegated to perform action.
func deleteButton(sender:FavoriteItemTableViewCell){
    //How should I delete. How can I get index path here
}

}

Q. What should I write in the deleteButton function ? I am unable to get the indexPath here so what should I do instead. I already have another button in cell and the delegation is working fine.

回答1:

you can get indexPath using table view point like this

let buttonPosition : CGPoint = sender.convert(sender.bounds.origin, to: tableview)
let indexPath = tableview.indexPathForRow(at: buttonPosition)