2014-03-05 43 views
0

我有一個包含自定義單元格的collectionview,只要單元格在屏幕上可見時它們就會不斷重新加載。集合視圖向下滾動,然後向上滾動,以便再次顯示單元格。我想關閉它,並希望單元格只加載一次,而不是每次刷新時都可以看到它們。這是我初始化單元的代碼。UICollectionView單元在它們變得可見時不斷重新加載

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath: (NSIndexPath *)indexPath{ 

    NSLog(@"cell row %d is being refreshed", indexPath.row); 
    static NSString *CellIdentifier = @"Cell"; 

    LevelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath]; 
    Level *levelTemp =[levels objectAtIndex:indexPath.item]; 

    [[cell levelNumber]setText:[NSString stringWithFormat:@"Level %@",levelTemp.level]]; 

    DataClass *obj=[DataClass getInstance]; 
    obj.totalC=obj.totalC+([levelTemp.comp_questions intValue]); 
    obj.totalQ=obj.totalQ+([levelTemp.max_questions intValue]); 
    int unlockA = [levelTemp.unlockAmount intValue]; 

    return cell; 
} 
+3

不,不,不。這正是表格視圖和集合視圖如何設計的。你只需要保持與屏幕上顯示的內容一樣多的單元格......如果你試圖將所有這些單元格保存在內存中,就會有巨大的性能下降...... – nhgrif

+0

njgrif是正確的,但是如果你不關心性能打擊,給每個單元格一個唯一的單元格標識符,它將在每個單元格中生成一次,而不是重新使用它們。 – box86rowh

+0

實際上並不是這樣,@ box86rowh這實際上是兩個世界中最糟糕的。它將保持單元格在內存中......但它仍然會在它們放到屏幕上之前重新加載它們。 – nhgrif

回答

0

這是一個壞主意。處理這個問題的正確方法是讓levels存儲所有需要的數據,從集合視圖中抓取下一個單元格,並使用levels中的數據填充它。這是記憶效率和時間效率。


有一個NSMutableArray持有LevelCell秒。由於單元格被請求的順序未知,因此您需要預先初始化該數組。它需要與levels的尺寸相同,且需要的值需要是[NSNull null]

self.cells = [NSMutableArray arrayWithCapacity:[levels count]]; 
for (NSUInteger i = 0; i < [levels count]; ++i) { 
    self.cells[i] = (id)[NSNull null]; 
} 

這可以在你的-viewDidLoad也許作爲一個延遲加載特性。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Look to see if there is a cell at this index 
    LevelCell *cell = self.cells[indexPath.item]; 

    if (cell == (id)[NSNull null]) { 
     NSLog(@"cell row %d is being refreshed", indexPath.item); 
     static NSString *CellIdentifier = @"Cell"; 

     cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath]; 
     Level *levelTemp =[levels objectAtIndex:indexPath.item]; 

     [[cell levelNumber]setText:[NSString stringWithFormat:@"Level %@",levelTemp.level]]; 

     DataClass *obj=[DataClass getInstance]; 
     obj.totalC=obj.totalC+([levelTemp.comp_questions intValue]); 
     obj.totalQ=obj.totalQ+([levelTemp.max_questions intValue]); 
     int unlockA = [levelTemp.unlockAmount intValue]; 

     // save the new cell in the array. 
     self.cells[indexPath.item] = cell; 
    } 

    return cell; 
} 

最後注意:self.cells在數據更新時不會更新。您需要手動執行此操作。所有更改,插入和刪除都需要在levelsself.cells之間鏡像。

再次,這是一個壞主意。真的,不要這樣做。

相關問題