簡體   English   中英

CollectionViewCell在滾動時會產生隨機的事物

[英]CollectionViewCell makes random things while scrolling

點擊一個單元格后,我的單元格將背景變為黃色。 當其背景為黃色時,它將恢復為默認顏色。

一切正常,但是如果我開始滾動,則某些單元格會將backgroundColor更改為黃色,盡管未選中它。 不幸的是,它具有隨機行為。

我更改了使用alloc init創建單元格的操作,但是現在,它拋出一個錯誤,提示:

cells must be retrieved by calling -dequeueReusableCellWithReuseIdentifier:forIndexPath:

我使用情節提要來處理單元格中的元素,並像

 UICollectionViewCell *cell = [collectionView
                              dequeueReusableCellWithReuseIdentifier:@"Number Cell"
                              forIndexPath:indexPath];




UILabel *label = (UILabel *)[cell viewWithTag:100];
label.text = [NSString stringWithFormat:@"%i", indexPath.item + 1];

有什么建議么?

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

    UICollectionViewCell *cell = [collectionView
                                  dequeueReusableCellWithReuseIdentifier:@"Number Cell"
                                  forIndexPath:indexPath];


    UILabel *label = (UILabel *)[cell viewWithTag:100];
    label.text = [NSString stringWithFormat:@"%i", (int)indexPath.item + 1];

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];


        if ([cell.backgroundColor isEqual:[UIColor yellowColor]]) {

            cell.backgroundColor  = [UIColor clearColor];
        } else {    

            cell.backgroundColor  = [UIColor yellowColor];           
        }

}

我假設,

- (void)collectionView:(UICollectionView *)collectionView
    didSelectItemAtIndexPath:(NSIndexPath *)indexPath

每當我點擊一個單元格時都會調用它。 因此,當它具有清晰的顏色時,我將顏色更改為黃色,反之亦然。

如果您要在單元格的setSelected:方法中設置黃色背景顏色,則應該自動發生這種情況,假設如果有人調用[cell setSelected:NO] ,您也將其設置回正常狀態。

如果這不起作用,則可以在出單元格后或在單元格的prepareForReuse:方法中重置單元格的背景色。

暫無
暫無

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

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