UICollectionViewCell更改背景 [英] UICollectionviewcell change background

查看:317
本文介绍了UICollectionViewCell更改背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我知道部件号和项目号,如何更改单元格中的背景?下面的代码显示了我如何尝试执行此操作.

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, 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
}

如果您使用的是UICollectionViewCell的自定义子类,则还可以通过实现prepareForReuse方法将其重置为默认值.

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

这篇关于UICollectionViewCell更改背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆