If I add a UISwitch control to each of my table view cells, how can I tell which cell it belongs to?
First of all, fix the memory leak:
UISwitch *switchEnabled = [[[UISwitch alloc] initWithFrame:frameSwitch] autorelease];
Then pick one of these options:
switchEnabled.tag = someInt; // before adding it to the cell
NSLog(@"switched %d",switch.tag); // to see which switch was toggled
or
UITableViewCell *parentCell = switchEnabled.superview;
// + some magic to see which cell this actually is
In your action method, you can cast the superview
of the passed-in UISwitch
(which is the UITableViewCell
itself), then pass that to the tableView
's indexPathForCell
method.
indexPathForCell
will return a NSIndexPath
object, which you can then use to index to your datamodel to modify. Then all you gotta do is call reloadData
on your tableView
.
Also, in cellForRowAtIndexPath
, you should set the UISwitch
's state based on your model.