点击集合视图单元格更改图像

时间:2013-01-10 20:03:55

标签: ios uitableview uicollectionview

我有一个收集单元格,想要在触摸时更改图像,然后再返回,我应该如何构建它?

突出显示(在下面工作正常)后,我希望它再次触摸时返回旧图像。谢谢。在viewWillDissapear,我想知道哪些单元格被突出显示。

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    UIImage *backGround =[UIImage imageNamed:@"IconHighlight.png"];
    UIImageView *av = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, backGround.size.width, backGround.size.height)];
    av.backgroundColor = [UIColor clearColor];
    av.opaque = NO;
    av.image = backGround;

    [[collectionView cellForItemAtIndexPath:indexPath] setBackgroundView:av];
    [[collectionView cellForItemAtIndexPath:indexPath].backgroundView setTag:1];
}

1 个答案:

答案 0 :(得分:4)

创建CustomCell - UICollectionViewCell的子类。自定义init到以下

//CustomCell.m
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        backgroundImageView.image = [UIImage imageNamed:@"background.png"];
        highlightImageView.image = [UIImage imageNamed:@"highlight.png"];
        self.backgroundView = backgroundImageView;
        _isHighlight = -1;
    }
    return self;
}

-(void)tapToChangeBackGround{

    self.isHighlight = -self.isHighlight;

    if (self.isHighlight==1) {
        self.backgroundView = highlightImageView;
    }
    else{
        self.backgroundView = backgroundImageView;
    }
}

//didSelect
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    CustomCell *cell = (CustomCell *)[collectionView cellForItemAtIndexPath:indexPath];
    [cell tapToChangeBackGround];
}