I have a UICollectionView where I represent data taken from a SQLite database. When I scroll up and down the CollectionView I have problems with a UISwitch:
-(UICollectionViewCell *)collectionView:(UICollectionView *)cv
cellForItemAtIndexPath:(NSIndexPath *)indexPath {
city_setlist *cellValue = [self.arr objectAtIndex:indexPath.row];
UISwitch *onoff=(UISwitch *) [cell viewWithTag:106];
onoff.tag=[cellValue._id_setlist intValue];
if([cellValue._was_there isEqualToString:@"1"])
[onoff setOn:YES animated:YES];
else
[onoff setOn:NO animated:YES];
}
If I don’t scroll, data is ok, but if I start scrolling up and down the CollectionView, the UISwitch is randomly on where it should be off and vice versa. What am I doing wrong?
Cells can be reused in a tiling view. This code looks like it assumes the cell is not reused:
This changes the tag of the switch to be something other than 106, I assume. This means that if the cell is later reused, it will no longer be 106, and the top line will return nil. Try removing the second line I’ve quoted. (You could also confirm this is the problem by logging the
onoffvalue you get in the first line while scrolling.)In general, using tags is kinda mucky; you might find it cleaner by defining a subclass for your cell and hooking up the UISwitch to a property (via, say, an outlet).