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新しく選択したセルと以前に選択したセルの色を設定するだけで十分です。

更新:一度に1 つのセルしか選択できない場合は、選択したセルのインデックス パスを覚えておく必要があります。

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 に答える