【问题标题】:Highlight cells in CollectionView在 CollectionView 中突出显示单元格
【发布时间】:2013-11-02 22:52:30
【问题描述】:

我正在 iOS 中构建一个应用程序,我希望 CollectionView 中的单元格在被触​​摸时突出显示,就像普通按钮一样。如何在 didSelectItemAtIndexPath:(NSIndexPath *)indexPath 方法中实现这一点?

【问题讨论】:

  • 更改该单元格的背景颜色。

标签: ios highlight cells collectionview


【解决方案1】:

为什么不能通过cocoa pods改变背景颜色?我新建了一个用户自定义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];
}

【讨论】:

    【解决方案2】:

    如果您对单元类进行了子类化,请将其放入您的 .m 文件中

    - (void)setSelected:(BOOL)selected
    {
        if(selected)
        {
            self.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.5];
        }
        else
        {
            self.backgroundColor = [UIColor whiteColor];
        }
    }
    

    【讨论】:

      【解决方案3】:

      试试这样的:

      - (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
      【解决方案4】:

      试试这个

      cell.selectedBackgroundView.backgroundColor = [UIColor greenColor];
      

      【讨论】: