Question

I have a UITableView with prototype cells that have a UISwitch on them. When the user taps the switch on any particular cell, I need to determine which object in my datasource has had its switch toggled.

Here is my method for the switch:

- (IBAction)completeSwitchTapped:(id)sender {
      UITableViewCell *cell = (UITableViewCell *)[sender superview];
      NSIndexPath *indexPath = [self.itineraryTableView indexPathForCell:cell];


      NSLog(@"cell row is: %d in section: %d", indexPath.row, indexPath.section);
}

But this always returns row 0 in section 0 regardless of which row or section was picked.

How do I properly return the correct cell which contains the switch? Clearly [sender superview] isn't working and I'm considerably at a loss for how to reference the cell.

Thanks!

Was it helpful?

Solution

Try something like this:

UIView *superview = sender.superview;
while (![superview isKindOfClass:[UITableViewCell class]] && superview.superview != nil) {
    superview = superview.superview;
}
NSIndexPath *indexPath = [self.itineraryTableView indexPathForCell:superview];

OTHER TIPS

When creating the button/switch, set it's tag to the cell row or some other meaningful value. Then simply extract sender.tag when the IBAction method is invoked, to retrieve the cell row.

When I have to do buttons and switches like this in my own tables, I usually subclass UIButton or UISwitch and in my subclass, I add a ".indexPath" or ".row" property to my subclassed control.

Which I set when I return the freshly populated (or reset) table view cell in "cellForRowInIndexPath:"

That way, when your switch or button is touched, you'll have a property that has the correctly set row index ready for you to work with.

A much more straightforward & less janky solution versus doing "superview.superview".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top