I have a UITableViewCell
with UISwitch
as accessoryview of each cell. When I change the value of the switch in a cell, how can I know in which row
If you set the tag
property to the row number (as suggested by other answers), you have to update it every time in tableView:cellForRowAtIndexPath:
(because a cell can be reused for different rows).
Instead, when you need the row number, you can walk up the superview
chain from the UISwitch
(or any other view) to the UITableViewCell
, and then to the UITableView
, and ask the table view for the index path of the cell:
static NSIndexPath *indexPathForView(UIView *view) {
while (view && ![view isKindOfClass:[UITableViewCell class]])
view = view.superview;
if (!view)
return nil;
UITableViewCell *cell = (UITableViewCell *)view;
while (view && ![view isKindOfClass:[UITableView class]])
view = view.superview;
if (!view)
return nil;
UITableView *tableView = (UITableView *)view;
return [tableView indexPathForCell:cell];
}
This doesn't require anything in tableView:cellForRowAtIndexPath:
.