[英]CollectionView Highlights incorrect Cell When Scrolling
我有一個UICollectionView
。 用戶單擊單元格時,單元格的顏色變為紅色。 我已經編碼了上面的部分,並且效果很好。
但是,當我在下面滾動時,集合視圖中的其他單元格已用紅色突出顯示。 我確定它沒有被選中,只是突出顯示了。
我該如何解決。
我的代碼如下:
cellForItemAtIndexPath方法
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"cell";
ViewCell *vc = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
vc.vciv.image = [arrayOfImages objectAtIndex:indexPath.row];
return vc;
}
didSelectItemAtIndexPath方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
if([items containsObject:allItem[indexPath.row]] ){
UICollectionViewCell *c =[collectionView cellForItemAtIndexPath:indexPath];
c.backgroundColor = [UIColor clearColor];
} else {
UICollectionViewCell *c =[collectionView cellForItemAtIndexPath:indexPath];
c.backgroundColor = [UIColor redColor];
}
隨着集合視圖單元的重用,您需要確保在cellForItemAtIndexPath:
方法中未突出顯示出隊的單元:
UICollectionViewCell *vc = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
vc.backgroundColor = [UIColor clearColor];
此代碼將在出隊時始終清除單元格的背景。 如果需要保留突出顯示,則需要存儲要突出顯示的單元格的indexPath
,並檢查該列表中的當前單元格。
編輯
看來您的items
變量非常適合執行此操作。 所以你會做:
UICollectionViewCell *vc = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
vc.backgroundColor = [items containsObject:allItem[indexPath.row]] ? [UIColor redColor] : [UIColor clearColor];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.