簡體   English   中英

UICollectionView重復單元格

[英]UICollectionView repeats cell

我有一個UICollectionView ,我在其中顯示從Internet下載的圖像網格。 我正在使用SDWebImage加載圖像。 我面臨的問題是,當我滾動瀏覽UICollectionView ,有時單元格會重復,顯示相同的圖像。 但是當單元格滾出視圖然后返回時,它具有正確的圖像集。

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

    NSString *CellIdentifier = @"Gallery_Cell";

    GalleryCell *cell;

    if (cell==nil) {
        cell= (GalleryCell *)[self.flowCollection dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];

        ImageItem *dets = [self.imageList objectAtIndex:indexPath.row];

        NSURL *mainImageURL = [NSURL URLWithString:dets.smallImageURL];

        cell.image.contentMode = UIViewContentModeScaleAspectFill;
        cell.image.clipsToBounds = YES;                

        [cell.image setImageWithURL:mainImageURL placeholderImage:nil];

    }

    return cell;

}

這有發生在其他人身上嗎? 非常感謝任何指針。

GalleryCell.m你需要添加prepareForReuse方法,並在那里使_image變量無效(假設你在單元格中有一個image _image ):

- (void)prepareForReuse {
    [super prepareForReuse];
    [self setHighlighted:NO];

    _image = nil;
}

“UICollectionView類參考”中說明了以下內容:“如果您為指定的標識符注冊了類,並且必須創建新的單元格,則此方法通過調用其initWithFrame:方法來初始化單元格。對於基於nib的單元格,此方法從提供的nib文件加載單元格對象。如果現有單元格可用於重用,則此方法將調用單元格的prepareForReuse方法。“

你有GalleryCell單元類的prepareForReuse方法嗎?

你的單元類應該是UICollectionReusableView類的子類。 檢查一下。

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

NSString *CellIdentifier = @"Gallery_Cell";

GalleryCell *cell;

if (cell==nil) {
    cell= (GalleryCell *)[self.flowCollection dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];

    ImageItem *dets = [self.imageList objectAtIndex:indexPath.row];

    NSURL *mainImageURL = [NSURL URLWithString:dets.smallImageURL];

    [cell.image setImage:[UIImage new]];

    cell.image.contentMode = UIViewContentModeScaleAspectFill;
    cell.image.clipsToBounds = YES;                

    [cell.image setImageWithURL:mainImageURL placeholderImage:nil];

}

return cell;

}

使用這種方法這個vl絕對可以100%工作。

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath;
{
   GalleryCell *cell1 = (GalleryCell*)[_resumeCollectionView cellForItemAtIndexPath:indexPath];
    cell1= nil;

}

由於單元格正在重用,因此必須在cellForIndexPath:中無條件地設置其內容。 您的代碼最終會設置圖像,但它會使圖像暫時保留為舊值 - 在重用之前設置的值。

一個快速的解決方案是(可能)使用占位符圖像提供setImageWithURL調用。 我不知道SDImage庫,但很好的猜測它會立即將imageView的圖像設置為占位符圖像(如果提供了一個)。

如果您沒有或不想要占位符圖像,可以在UICollectionViewCell子類中實現prepareForReuse在那里清除UICollectionViewCell

我最終使用UICollectionView的“didEndDisplayingCell”方法並結束當前的Image下載並將圖像設置為nil。 這完美地工作,沒有更多的“洗牌”或重復圖像! :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM