Search code examples
iosuitableviewswiftibaction

How do I pass indexPath (not indexPath.row) into my IBAction for my UITableViewCell


I am developing a to-do application. In my app, I press a checkbox button to delete a row. I write this code in order to pass the indexPath.row into my checkbox button:

cell.checkbox.tag = indexPath.row
cell.checkbox.addTarget(self, action: "checkAction:", forControlEvents: .TouchUpInside)

The first code allows me access to indexPath.row and the second one allow me to create a function for when my button is pressed. This is the function I use for when the button is pressed:

@IBAction func checkAction(sender: UIButton) {
    taskMgr.removeTask(sender.tag)
    tblTasks.reloadData()
}

Now, I want to add animation for when it deletes, so it doesn't look so sudden. The code I would use is this:

tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

However, I only have access to indexPath.row in my checkAction function. How do I get access to the indexPath (without sacrificing indexPath.row)?


Solution

  • Tags can give you an erroneous row if you move rows around or add or delete rows until you reload the entire table. So, instead of using tags, you can use indexPathForRowAtPoint: in your button method to get the indexPath.

    @IBAction func checkAction(sender: UIButton) {
    
        let point = sender.convertPoint(CGPointZero, toView: self.tableView)
        let indexPath = self.tableView.indexPathForRowAtPoint(point)
        taskMgr.removeTask(indexPath.row)
        tblTasks.reloadData()
    }