これは、スクロール時にセルが再利用されるために発生します。モデル内のすべての行の「強調表示された」ステータスを保存する必要があります (配列や など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
}
}