在CollectionView中突出显示单元格

6

我正在开发一款iOS应用程序,希望在CollectionView中的单元格被点击时能够高亮,类似于普通按钮的效果。我应该如何在didSelectItemAtIndexPath:(NSIndexPath *)indexPath方法中实现此功能?


更改该单元格的背景颜色。 - user1673099
4个回答

7

尝试类似于这样的方式:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    .....
    if (cell.selected) {
        cell.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:153/255.0 alpha:1]; // highlight selection
    }
    else
    {
        cell.backgroundColor = [UIColor clearColor]; // Default color
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell* cell = [collectionView  cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:153/255.0 alpha:1]; //     //cell.lblImgTitle.text = @"xxx";
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell* cell = [collectionView  cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
}

我通过在didHighlightItemAtIndexPath和didUnhighlightItemAtIndexPath方法中更改单元格中图片的Alpha值来解决了这个问题。无论如何,我会将你的答案设置为正确答案。谢谢。 - diogo.appDev
1
为什么不在答案中发布您是如何解决问题的呢?这对其他人会很有帮助... Diogo-appdev - Narasimha Nallamsetty

5
如果您继承了cell类,请将以下代码放置在您的.m文件中。
- (void)setSelected:(BOOL)selected
{
    if(selected)
    {
        self.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.5];
    }
    else
    {
        self.backgroundColor = [UIColor whiteColor];
    }
}

0
为什么无法通过CocoaPods更改背景颜色?我新建了一个自定义的collectionView单元格类。
   - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
        CHSMenuControlCell *cell = (CHSMenuControlCell*)[collectionView  cellForItemAtIndexPath:indexPath];
        cell.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:153/255.0 alpha:1]; //     //cell.lblImgTitle.text = @"xxx";
    }

    - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    CHSMenuControlCell *cell = (CHSMenuControlCell *)[collectionView  cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
}

0

试一下这个

cell.selectedBackgroundView.backgroundColor = [UIColor greenColor];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接