I have a UITableView with cells that contain a UISwitch control. It’s similar to the table view in the iPhone’s Clock app shown below…

(source: epicself.com)
In my app’s cellForRowAtIndexPath method, I create and attach the UISwitch control like so…
CGRect frameSwitch = CGRectMake(215.0, 10.0, 94.0, 27.0);
UISwitch *switchEnabled = [[UISwitch alloc] initWithFrame:frameSwitch];
[switchEnabled addTarget:self action:@selector(switchToggled:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = switchEnabled;
My question is, when the switch is toggled by the user and the switchToggled method is called, how can I tell which table cell it belongs to? I can’t really do much with it without knowing it’s context.
Thanks so much in advance for your help!
In your action method, you can cast the
superviewof the passed-inUISwitch(which is theUITableViewCellitself), then pass that to thetableView‘sindexPathForCellmethod.indexPathForCellwill return aNSIndexPathobject, which you can then use to index to your datamodel to modify. Then all you gotta do is callreloadDataon yourtableView.Also, in
cellForRowAtIndexPath, you should set theUISwitch‘s state based on your model.