发生这种情况是因为滚动时会重复使用单元格。您必须为模型中的所有行存储“突出显示”状态(例如在数组或 中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
}
}