Two superviews are better than one

So I have a table view that is built by using a custom cell that I built in Interface Builder and load up in my view controller. This UITableViewCell has a bunch of UIButton controls right off the root of the cell view in it that I need to snag the action on, and of course there can be a lot of cells in the table. In order to do this as compactly as possible, I wanted to just create one IBAction method, and funnel all button presses to that method. Then, inside the method, I would just read the tag of the sender to decide what button was pressed, and then back up one level to get the cell, ask the table for the index path of that cell, and then I would know which row to act on.

Well of course it did not work as expected the first time. For some reason, when I asked the table for the index path of the cell, it would always return a nil index path. So here is the final code that works.

UITableViewCell *cell = (UITableViewCell *)sender.superview.superview;
NSIndexPath *path = [contactsTable indexPathForCell:cell];

As I studied the problem, I discovered that the first superview off the sender does not get you far enough back, you have to go back another superview.

BTW, thanks to Leo Fender, born this day in 1909, for founding a company with such awesome products.

Leave a Reply