UICollectionviewcell change background

2019-02-28 05:53发布

问题:

How to change the background in the cell if I know the section number and the item number? The code below shows how I tried to do it.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CalendarCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.titleLabel.text = [NSString stringWithFormat:@"%i",indexPath.item-dayStart+2];

    if (indexPath.section == todayMonthSection && indexPath.item == dayPlusShift){

        cell.backgroundColor = [UIColor colorWithRed:60.0/255.0 green:162.0/255.0 blue:161.0/255.0 alpha:1];
        cell.titleLabel.textColor = [UIColor whiteColor];

    }

    return cell;

But if I do so during scrolling painted not just the relevant cell.

回答1:

What you're seeing is the cell getting reused as the view scrolls, the reused cell still has the background color from an earlier use. Fix by handling both branches of the case (all cases) when you configure, e.g.:

if (indexPath.section == todayMonthSection && indexPath.item == dayPlusShift){

    cell.backgroundColor = [UIColor colorWithRed:60.0/255.0 green:162.0/255.0 blue:161.0/255.0 alpha:1];
    cell.titleLabel.textColor = [UIColor whiteColor];
} else {
    cell.backgroundColor = [UIColor whiteColor];  // whatever the default color is
}

If you're using a custom subclass of UICollectionViewCell, you may also reset to defaults by implementing the prepareForReuse method.



回答2:

you are using CalendarCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; the collection view is dequeueing ReusableCells so when scrolling it than again uses the old cells changing your desired requirement.it happens with background color and images

add this line before condition

CalendarCollectionViewCell *cell=[NSBundle mainBundle] loadNibNamed:@"CalendarCollectionViewCell" owner:self options:nil] objectAtIndex:0];

do not use

if(!cell){....