UICollectionviewcell 改变背景 [英] UICollectionviewcell change background

查看:23
本文介绍了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天全站免登陆