Getting UITableViewCell from UITapGestureRecognizer

iOSBeginner picture iOSBeginner · Mar 31, 2015 · Viewed 7.4k times · Source

I have a UITableView with multiple sections and in my cellForRowAtIndexPath method I add a UITapGestureRecognizer to the cell's imageView (each cell has a small image). I have been successful in accessing that image (in order to change it) by using:

var imageView : UIImageView! = sender.view! as UIImageView

What I need to do now, however, is access the cell's data, which I believe means I need to be able to access the cell in order to get the section and row number. Can anyone advise on how to do this? The idea is that I am changing the image to an unchecked checkbox if the task is done, but then in my data I need to actually mark that task as done.

Answer

Ian picture Ian · Mar 31, 2015

In your function that handles the tap gesture recognizer, use tableView's indexPathForRowAtPoint function to obtain and optional index path of your touch event like so:

func handleTap(sender: UITapGestureRecognizer) {
    let touch = sender.locationInView(tableView)
    if let indexPath = tableView.indexPathForRowAtPoint(touch) {
        // Access the image or the cell at this index path
    }
}

From here, you can call cellForRowAtIndexPath to get the cell or any of its content, as you now have the index path of the tapped cell.