【问题标题】:Changing background color of not highlighted cell in UICollectionView更改 UICollectionView 中未突出显示的单元格的背景颜色
【发布时间】:2014-04-25 03:23:22
【问题描述】:

当我用这段代码点击单元格时,我设法设置了单元格背景颜色:

- (void) collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:   (NSIndexPath *)indexPath
{
    NSLog(@"highlighted cell at index path %ld", (long)indexPath.row);

    UICollectionViewCell* cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor blueColor];

}

但是我有两个问题

1:我在一个视图中显示 6 个单元格,然后我滑动显示其他单元格,其中一些单元格也以蓝色背景突出显示

2:我选择单元格A并将背景颜色更改为蓝色后,当我选择B时,A中的背景颜色并没有变回白色,我怎么能把它改回来?

谢谢!

【问题讨论】:

    标签: ios uicollectionview


    【解决方案1】:

    您需要在 collectionView:cellForItemAtIndexPath: 方法中正确重置单元格。

    if (/* cell is highlighted */) {
        cell.contentView.backgroundColor = [UIColor blueColor];
    } else {
        cell.contentView.backgroundColor = [UIColor whiteColor]; // use whatever is appropriate
    }
    

    这当然要求您跟踪应该突出显示哪些单元格。

    【讨论】:

    • erm,我该如何跟踪?
    • 另外,如果我选择单元格 B,单元格 A 仍然保持蓝色。我需要将其从视图中滑出以使其恢复为白色背景。
    • 如何跟踪取决于您是只支持一个突出显示的单元格还是多个。如果是单一的,您可以添加一个 ivar 来跟踪与单元格相关的一些键。如果有多个,那么您应该为数据源中的每个单元格添加一个附加值。
    • 我只做一个突出显示。我有 18 个项目。所以我想让用户一次选择一项。他们可能点击 A 并且 A 会有蓝色背景,但是如果他们点击 C,A 应该变回白色背景,而 C 是蓝色背景。
    • didHighlightItemAtIndexPath 中,您将当前突出显示的单元格的背景更新为白色。然后将当前单元格更新为蓝色。然后设置一个 ivar,指示当前突出显示的单元格。此 ivar 用于我在答案中发布的 if 语句中,因此在滚动集合视图时会突出显示正确的单元格。
    【解决方案2】:

    如果您只需要在手指触摸单元格时将单元格突出显示为蓝色背景,您可以在didUnhighlightItemAtIndexPath 中将颜色改回白色。

    - (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
    {
        NSLog(@"unhighlighted cell at index path %ld", (long)indexPath.row);
    
        UICollectionViewCell* cell = [collectionView cellForItemAtIndexPath:indexPath];
        cell.contentView.backgroundColor = [UIColor whiteColor];
    }
    

    这使得其他单元格不会以相同的背景颜色被回收(问题 1),并且在点击单元格 B 之前抬起手指后,单元格 A 会立即恢复为默认颜色(问题 2)。

    更多详情请见this question and its answers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多