我嘗試在iOS中重新加載UICollectionView時有一個probem。卸載UICollectionView並重新加載?
我使用它來顯示遊戲中的關卡。
collectionview由10個單元組成。單元格的內容取決於級別是否解鎖。如果關卡解鎖,那麼單元顯示關卡(一個自定義的UIView),否則顯示一個圖像。 我不得不爲此創建單獨的單元格標識符,並且所有內容在加載時都完美顯示。
我的問題是當一個用戶正在玩一個解鎖的關卡,然後解鎖下一個關卡。當用戶從遊戲視圖返回到級別選擇視圖時,單元格未正確重新加載(只在自定義視圖應該顯示的位置顯示空白,圖像正確顯示)。
我試圖用viewWillAppear中的級別卸載數組,然後調用[collectionview reloadData] ;,然後加載級別並重新加載collectionview,但這沒有幫助。
如何在顯示視圖時清空整個collectionview並重新創建單元標識符?
謝謝
-EDIT!更新了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];
}
而且在項目的細胞在指數路徑
- (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;
}
你說的「自定義視圖」是空的,但「圖像正確顯示」 。我不知道如何調和這兩個陳述。但在回答你的問題時,'reloadData'是正確的技術。我會在各種'UICollectionViewDataSource'中放入日誌語句或調試斷點,並確認正在報告正確的值。這個集合視圖最初是否正確工作,但在「解鎖」一個關卡後不正確? – Rob
感謝您的評論羅布。 對不起,任何困惑,但它就像是重新加載時更改的單元格沒有正確更改。 我試圖NSLog的數據,它是正確的。但是,看起來像是當單元格被創建後,一旦它沒有被「重新創建」,就會出現WillAppear。它們在退出視圖並再次打開時正確顯示。所以看起來問題是單元格仍然在內存中而不是重新加載? – CCDEV
通常你會在你的'viewWillAppear'或'viewDidAppear'中編寫代碼,它會調用'reloadData'(在調用'super'後)。爲了重複我自己,我會將log語句放在'numberOfItemsInSection'和'cellForItemAtIndexPath'中,這樣您就可以確認reloadData在視圖重新出現時被正確調用,因此您可以在該點檢查模型結構的各種值。 – Rob