Note that there are some explanatory texts on larger screens.

plurals
  1. POiPhone UISwitch and TableView saving state
    text
    copied!<p>I am trying to put a <code>UISwitch</code> into a <code>UITableView</code>. I have looked at this question <a href="https://stackoverflow.com/questions/1322754/uiswitch-inside-custom-uitableviewcell-not-available">here</a> and <a href="https://stackoverflow.com/questions/2562048/uitableviewcell-custom-accessory-get-the-row-of-accessory">here</a>. Since the table view reuses cells I need to save the state of the cells. I achieve this by having a <code>NSMutableDictionary</code> where the row of the cell maps the state (true or false) of the UISwitch. The problem I am running into is identifying the index of the UISwitch in the TableView. I think something is wrong with the @selector statement. This has been driving me crazy for the past 2 hours. Is this the right way to do it and why do I change the state of any of the UISwitch it always reports with the same log message (see below). Any help is greatly appreciated. Here is some snippets of my code ....</p> <p><strong>cellForRowAtIndexPath</strong></p> <pre><code>//Need to construct if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; UISwitch *temp = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease]; //Add a callback when the value is changed [temp addTarget:self action:@selector(switchButtonChanged:forEvent:) forControlEvents:UIControlEventValueChanged]; //Set the acessory view to the UISwitch cell.accessoryView = temp; } </code></pre> <p><strong>Callback Method</strong></p> <pre><code>- (void)switchButtonChanged:(id)sender forEvent:(UIEvent *)event { UISwitch *tempSwitch = (UISwitch *) sender; NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:[[[event touchesForView:sender] anyObject] locationInView:tableView]]; NSNumber *isChecked = [[[NSNumber alloc] initWithBool:tempSwitch.on] autorelease]; NSNumber *row = [[[NSNumber alloc] initWithInteger:indexPath.row] autorelease]; [self.selectedItems setObject:isChecked forKey:row]; NSLog(@"Row %@ is now %@", row, [self.selectedItems objectForKey:row]); } </code></pre> <p><strong>Log</strong></p> <pre><code>Row 0 is now (null) Row 0 is now (null) Row 0 is now (null) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload