选择单元格后,我想处理更改单元格外观.我想委托方法collectionView:didSelectItemAtIndexPath:&collectionView:didDeselectItemAtIndexPath:是我应该编辑细胞.
-(void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
DatasetCell *datasetCell =
(DatasetCell *)[collectionView cellForItemAtIndexPath:indexPath];
[datasetCell replaceHeaderGradientWith:[UIColor skyBlueHeaderGradient]];
datasetCell.backgroundColor = [UIColor skyBlueColor];
}
Run Code Online (Sandbox Code Playgroud)
-(void)collectionView:(UICollectionView *)collectionView
didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
DatasetCell *datasetCell =
(DatasetCell *)[collectionView cellForItemAtIndexPath:indexPath];
[datasetCell replaceHeaderGradientWith:[UIColor grayGradient]];
datasetCell.backgroundColor = [UIColor myDarkGrayColor];
}
Run Code Online (Sandbox Code Playgroud)
这种方法很好,除非重用单元格.如果我在索引(0,0)处选择单元格,它会更改外观,但是当我向下滚动时,会有另一个单元格处于选定状态.
我相信我应该使用这种UICollectionViewCell方法-(void)prepareForReuse来准备细胞以便重复使用(即,将细胞外观设置为非选择状态),但它给我带来了困难.
-(void)prepareForReuse {
if ( self.selected ) {
[self replaceHeaderGradientWith:[UIColor skyBlueHeaderGradient]];
self.backgroundColor = [UIColor skyBlueColor];
} else {
[self replaceHeaderGradientWith:[UIColor grayGradient]];
self.backgroundColor = [UIColor myDarkGrayColor];
}
}
Run Code Online (Sandbox Code Playgroud)
当我向后滚动到顶部时,索引(0,0)处的单元格处于取消选择状态.
当我刚刚使用cell.backgroundView属性时,为了防止这种情况发生在:
-(void)prepareForReuse { …Run Code Online (Sandbox Code Playgroud)