Matt Price
Matt Price

Reputation: 34629

Getting NSIndexPath of a row for UISwitch

I have a tableview with custom UITableViewCells, each row in the table has a UILabel, UISwitch and detail disclosure indicator.

I'm looking for the best method of capturing the UIControlEventChanged for the switch but I also need the NSIndexPath of the switch that changed to update Core Data.

I don't want the UISwitch as an accessory type either.

I've been googling this for hours and the solution that keeps popping up is to use

[switch addTarget:self action:@selector(switchTapped:) forControlEvents:UIControlEventChanged];

then in the switchTapped: method use the following to get the NSIndexPath

NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)[[sender superview] superview]];

Is there a better way of doing this? I already have UITableViewCell subclassed, can I put a method in this class to return the NSIndexPath for a given switch?

Thanks in advance for any help

Upvotes: 2

Views: 1739

Answers (2)

jrturton
jrturton

Reputation: 119242

I'll take another opportunity to link to my answer here - tags and view hierarchy walking are clunky, error prone and unnecessary, and I see them recommended all over the place in SO answers. You can find the index path of any control using its frame and the table view's indexPathForRowAtPoint: method.

Upvotes: 3

Bourne
Bourne

Reputation: 10312

Setting a proper tag for the switch in each row of the table is a feasible solution. Set the tag according to the indexpath of the row in which it is present.

That way you avoid the possible problems that might arise to changes in view hierarchy.

This post might also help you.

Upvotes: -1

Related Questions