Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I add a UISwitch control to each of my table view cells, how can I tell which cell it belongs to?

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...

alt text
(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!

like image 278
BeachRunnerFred Avatar asked Aug 11 '10 20:08

BeachRunnerFred


People also ask

How do I add a prototype cell to UITableView?

Choose iOS -> Source -> Cocoa Touch Class. Name the class TableCiewController and make it a subclass of UITableViewController. Go to the TableViewController. swift file and declare the following array.


2 Answers

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.

like image 127
Jacob Relkin Avatar answered Nov 08 '22 07:11

Jacob Relkin


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
like image 29
mvds Avatar answered Nov 08 '22 05:11

mvds