I have a probem when trying to reload a UICollectionview in iOS.
I am using it to display levels in a game.
The collectionview consists of 10 cells. The content of the cells depends if a level is unlocked. If the level is unlocked the cell displays the level (a custom UIView), else it displays an image. I had to create individual cell identifiers for this to work, and everything displays perfectly on load.
My problem is when a user is playing an unlocked level and then unlocks the next level. When the user navigates back from the game view to the level selection view, the cells are not reloaded correctly (just shows up empty where the custom views should be, the images display correctly).
I have tried to unload the array with levels in viewWillAppear and then calling [collectionview reloadData];, then loading the levels and reloading the collectionview again, but that does not help.
How can I empty the entire collectionview and recreate the cell identifiers when the view is displayed?
Thanks
-EDIT! UPDATED WITH CODE -
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
levelsArray = nil;
puzzlesArray = nil;
levelsArray = [[NSMutableArray alloc]init];
puzzlesArray = [[NSMutableArray alloc]init];
[collectionView reloadData];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:@"puzzles"];
puzzlesArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if ([puzzlesArray count] == 0) {
[self.navigationController popViewControllerAnimated:YES];
}
else {
NSLog(@"%i puzzles loaded", [puzzlesArray count]);
//Get alle puzzles for the current category
for (Puzzle *puzzle in puzzlesArray) {
if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"Category"] isEqualToString:[puzzle categoryName]]) {
[levelsArray addObject:puzzle];
}
}
}
NSLog(@"View will appear");
[collectionView reloadData];
}
And in the cell for item at index path
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath; {
BOOL isUnlocked = [self isPuzzleUnlocked:[indexPath row]];
if ([[NSUserDefaults standardUserDefaults]boolForKey:@"u"] == YES) {
isUnlocked = YES;
}
[self.collectionView registerNib:[UINib nibWithNibName:@"CVCell" bundle:nil] forCellWithReuseIdentifier:[NSString stringWithFormat:@"%@%d", kCellReuseIdentifier, indexPath.row]];
CVCell *cell = (CVCell *)[collectionView dequeueReusableCellWithReuseIdentifier:[NSString stringWithFormat:@"%@%d", kCellReuseIdentifier, indexPath.row] forIndexPath:indexPath];
[cell setPuzzleInfo:[levelsArray objectAtIndex:[indexPath row]] unlocked:isUnlocked];
return cell;
}