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!
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];
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
".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.