UICollectionviewcell change background

家住魔仙堡 提交于 2019-12-20 04:51: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){....


来源:https://stackoverflow.com/questions/20416350/uicollectionviewcell-change-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!