见世界

关于UICollectionView中ReusableCell的一个问题

需求:
在collectionView: cellForItemAtIndexPath: 方法中为不同cell更换背景图片。

症状:
滚动时背景图片没有出现在预期位置。

调试:
cell中加入label,text设为indexPath.item. 发现label出现叠加现象。

解决方案:
获取reusableCell后,删除所有subview。

代码:

//collection item
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                 cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
     UICollectionViewCell *myCell = [collectionView
                                    dequeueReusableCellWithReuseIdentifier:@"levelCell"
                                    forIndexPath:indexPath];
    //设置圆角
    myCell.layer.cornerRadius = 8;
    myCell.layer.borderWidth = 1;

    //删除已存在的subview
    for(UIView *view in myCell.subviews) {
        [view removeFromSuperview];
    }

    //item背景图片
    UIImageView *cellBg = [[UIImageView alloc] initWithFrame: myCell.bounds];
    NSString *theme = [Utils StatusOPValueAtKey:@"currentTheme"];
    NSString *imgName = [NSString stringWithFormat:@"%@_grid_bg_%ld.png", theme, (indexPath.item/3+1)*3 ];
    cellBg.image = [self getGrayImage:[UIImage imageNamed:imgName]];

    //将rank图片加入背景图片
    CGRect rankFrame = CGRectMake(0, 92, 90, 32);
    UIImageView *rank = [[UIImageView alloc] initWithFrame: rankFrame];
    rank.image = [UIImage imageNamed:@"HaiZei_rank_0.png"];
    [cellBg addSubview:rank];

    [myCell addSubview:cellBg];
    [myCell sendSubviewToBack:cellBg];

    return myCell;
}