ios – 更改UICollectionView单元格的背景

我有一个UICollectionView,我以编程方式创建.我希望收集视图的行为方式如下:
1. User touches cell
2. Cell background color changes
3. User releases touch
4. Cell background color changes

这应该是一个快速的颜色变化,恰好在选择器与执行抽头操作相关的选项之前发生,其中包含集合视图的视图控制器从堆栈中弹出.

我一直在看这个问题:UICollectionView cell change background while tap

其中有以下用于此目的的方法摘要:

// Methods for notification of selection/deselection and highlight/unhighlight events.
// The sequence of calls leading to selection from a user touch is:
//
// (when the touch begins)
// 1. -collectionView:shouldHighlightItemAtIndexPath:
// 2. -collectionView:didHighlightItemAtIndexPath:
//
// (when the touch lifts)
// 3. -collectionView:shouldSelectItemAtIndexPath: or -    collectionView:shouldDeselectItemAtIndexPath:
// 4. -collectionView:didSelectItemAtIndexPath: or -collectionView:didDeselectItemAtIndexPath:
// 5. -collectionView:didUnhighlightItemAtIndexPath:

我假设我只需要从“触摸开始”和“触摸结束”时执行上述方法之一.但是无论我做什么,看起来背景颜色都会发生变化,然后再改变.这是我尝试的一些不起作用的例子:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
 {
   //pop vc 
 }

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

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

这将导致单元格背景颜色仅更改为红色.我也看了这个问题:UICollectionView Select and Deselect issue并尝试实现[UICollectionView selectItemAtIndexPath:animated:scrollPosition:]并在didSelectItemAtIndexPath内调用它,但是这也没有.集合视图数据源和委托设置.

解决方法

问题在于,您正在更改亮点上的颜色,并将其更改为取消选择,而不是在高亮度上

你应该简单地改变一下:

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

到这个:

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

另外,如果您不希望稍等一下让您的高亮发生,您应该将集合视图的delayedContentTouches属性设置为NO

编辑:也确保你打电话

[collectionView deselectItemAtIndexPath:indexPath animated:NO];

在-didSelectItemAtIndexPath方法中

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...