What is an index path in Swift

Swift: How do I get the indexpath.row when a button is tapped in a cell?

Use an extension for UITableView to get the cell for any view:


@ Paulw11's response to setting up a custom cell type with a Delegate property that sends messages to table view is a good way to go, but it takes some work to set up.

I think it's a bad idea to search the table view cell's view hierarchy for the cell. It's fragile. If you later include your button in a view for layout purposes, this code will likely be corrupted.

The use of view tags is also problematic. You need to remember to set up the tags when creating the cell. If you use this approach in a view controller that is using view tags for a different purpose, you can have duplicate tag numbers and your code may not work as expected.

I created an extension for UITableView that allows you to get the IndexPath for any view contained in a table view cell. It will return a null if the view passed in actually doesn't fall in a table view cell. Below is the source file of the extension in its entirety. You can simply paste this file into your project and then use the included method to find the index path that contains any view.

To use it, you can simply call the method in the IBAction for a button that is in a cell:

(Note that the function only works if the passed view object is contained in a cell that is currently displayed on the screen. This is useful because a view that is not displayed on the screen is actually not part of a specific one Index path that will likely be reassigned to a different index path when the cell is recycled.)

TO EDIT:

You can download a working demo project that uses the aforementioned extension from Github: TableViewExtension.git