UIControlEventValueChanged for UISwitch in UITableViewCell firing while viewing scrolls

Can anyone explain why the UIControlEventValueChanged is triggered when the UISwitch is enabled in the tableview cell, but not if it is disabled while scrolling?

I have 100+ rows in my table with data being pulled from Core Data when UISwitch is off. UIControlEventValueChanged doesn't fire, but if I toggle the switch to ON when the switch (table row) appears, it fires UIControlEventValueChanged.

I am using the following to configure a cell

[customCell.seenSwitch addTarget:self action:@selector(seenSwitchChanged:) forControlEvents:UIControlEventValueChanged];

      

The visibleSwitchChanged method changes the BOOL value in Core Data to match the state of the switch.

When scrolling through the table view, it quickly stutters and catches when UIControlEventValueChanged is fired. I'm guessing because the tableview is looking for data from CoreData and seeSwitchChanged is also trying to access CoreData p>

If I comment out the above line, the table view scrolls smoothly.

Hope this explanation is clear enough.

Many thanks

Matt

EDIT

-(void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    ECCustomCell *customCell = (ECCustomCell *)cell;
    ECPerson *person = [self.fetchedResultsController objectAtIndexPath:indexPath];

    customCell.name.text = [person valueForKey:@"name"];
    customCell.seenSwitch.on = [[person valueForKey:@"seen"] boolValue];

    [customCell.seenSwitch addTarget:self action:@selector(seenSwitchChanged:) forControlEvents:UIControlEventValueChanged];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"customCell"];
    [self configureCell:cell atIndexPath:indexPath];

    return cell;    
}

      

+3


source to share


1 answer


I think you should check the dequeue result for nil and highlight the cell if that happens. I also think your theory is correct about setting the switch on the fly. A safeguard could be to use a scroll delegate hook in the table view to lazily set only the visible radio buttons.



- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self setMySwitches];
}

- (void)setMySwitches {

    for (NSIndexPath *path in [self.tableView indexPathsForVisibleRows]) {
        // like your cell config logic
    }
}

      

0


source







All Articles