2

我有一个带有代码的水平集合视图,用于突出显示/着色所选单元格。它突出显示被选中的单元格,但之后每 5 个单元格也会突出显示。知道发生了什么吗?

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    for(int x = 0; x < [cellArray count]; x++){
        UICollectionViewCell *UnSelectedCell = [cellArray objectAtIndex:x];
        UnSelectedCell.backgroundColor = [UIColor colorWithRed:0.2 green:0.5 blue:0.8 alpha:0.0];
    }
    UICollectionViewCell *SelectedCell = [cellArray objectAtIndex:indexPath.row];
    SelectedCell.backgroundColor = [UIColor colorWithRed:0.2 green:0.5 blue:0.8 alpha:1.0];
    cellSelected = indexPath.row;
    NSLog(@"%i", cellSelected);

}
4

2 回答 2

6

发生这种情况是因为滚动时会重复使用单元格。您必须为模型中的所有行存储“突出显示”状态(例如在数组或 中NSMutableIndexSet),并collectionView:cellForItemAtIndexPath:根据该行的状态设置单元格的背景颜色。

didSelectItemAtIndexPath其中设置新选择的单元格和先前选择的单元格的颜色就足够了。

更新:如果一次只能选择一个单元格,您只需记住所选单元格的索引路径。

selectedIndexPath为当前突出显示的行声明一个属性:

@property (strong, nonatomic) NSIndexPath *selectedIndexPath;

didSelectItemAtIndexPath中,取消突出显示前一个单元格,并突出显示新单元格:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.selectedIndexPath != nil) {
        // deselect previously selected cell
        UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:self.selectedIndexPath];
        if (cell != nil) {
            // set default color for cell
        }
    }
    // Select newly selected cell:
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    if (cell != nil) {
        // set highlight color for cell
    }
    // Remember selection:
    self.selectedIndexPath = indexPath;
}

cellForItemAtIndexPath中,使用正确的背景颜色:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Identifier" forIndexPath:indexPath];
    if ([self.selectedIndexPath isEqual:indexPath) {
        // set highlight color
    } else {
        // set default color
    }
}
于 2013-11-09T18:22:07.873 回答
0

我认为您使用可重复使用的单元格进行收集-这很重要。您在重用单元格之前设置默认背景颜色。

于 2013-11-09T18:19:03.830 回答