0

我想在單元格中的每個偶數位置UICollectionViewUICollectionViewCell指數不準確

顯示一個問號

我寫這樣的:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; 
if (indexPath.row %2 ==0){ 
       UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 20, 20)]; 
       [image setImage:[UIImage imageNamed:@"missing"]]; 
       [cell.contentView addSubview:image]; 
      } 

     return cell; 

} 

在我第一次看到UICollectionView - 圖像正在顯示屬性 - 每個偶數:0,2,4但當我開始左右水平滾動時,無論我的情況如何,圖片都被添加到幾乎每個單元格中:indexPath.row %2 ==0

我該如何預防nt呢?我怎樣才能確保即使在滾動索引路徑時也不會改變?

我寫ios7

回答

1

這是發生,因爲舊的細胞得到再利用,不重新設置它們的外觀。在collectionView:cellForItemAtIndexPath:if條件中添加一個else區塊,然後在那裏清理您的牢房。通過從單元格中刪除圖像視圖,或類似的東西。

你需要的是這樣的:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; 
    if (indexPath.row %2 ==0){ 
     UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 20, 20)]; 
     [image setImage:[UIImage imageNamed:@"missing"]]; 
     [cell.contentView addSubview:image]; 
    } 
    else { 
     // Code to clean up the cell goes here. 
    } 

    return cell; 
} 
+0

如何刪除圖片? – Dejell

+0

你有幾個選擇。一種是創建一個「UICollectionViewCell」的自定義子類,並在那裏爲圖像視圖添加一個屬性。然後,您可以通過該屬性輕鬆引用它。另一種方法是在添加標籤到圖像視圖時添加它,因此當您想要刪除它時,您可以在遍歷單元格子視圖時通過該標籤找到它。 – Macondo2Seattle

+0

謝謝 - 我只是寫了(UIView *查看cell.subviews) { if([view isKindOfClass:[UIImageView class]]) [view removeFromSuperview]; } – Dejell

0
  • (UICollectionViewCell *)的CollectionView:(UICollectionView *)的CollectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *電池=的CollectionView dequeueReusableCellWithReuseIdentifier :@「Cell」forIndexPath:indexPath];

    UIImageView * image = [[UIImageView alloc] initWithFrame:CGRectMake(50,50,20,20)];

    如果(indexPath.row%2 == 0){

    [image setImage:[UIImage imageNamed:@"missing"]]; 
    [cell.contentView addSubview:image]; 
    

    } 別的 {

    [image setImage:[UIImage imageNamed:@""]]; 
    [cell.contentView addSubview:image]; 
    

    }

    返回細胞; }