简体   繁体   中英

UICollectionviewcell change background

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.

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, eg:

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.

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){....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM