我的集合视图就像上层,当所选单元格全部消失时,我调用了一个动作:
- (IBAction)clearAction:(UIButton *)sender {
for (CustomCell *cell in self.buy_code_cv.visibleCells) {
if (cell.selected) {
[cell setSelected: NO];
}
}
}
在自定义单元格的.m
文件中:我覆盖了setSelected:
方法:
- (void)setSelected:(BOOL)selected {
[super setSelected:selected];
//self.selected = !selected;
if (selected) {
self.backView.backgroundColor = APP_COLOR;
self.number_label.textColor = [UIColor whiteColor];
self.multiple_label.textColor = [UIColor whiteColor];
}
// uncheck
else {
self.backView.backgroundColor = [UIColor whiteColor];
self.number_label.textColor = HexRGB(0x999999);
self.multiple_label.textColor = HexRGB(0xcccccc);
}
if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectedCustomCell:)]) {
[self.delegate didSelectedCustomCell:self];
}
}
如何在UICollectionView中解决此问题?
答案 0 :(得分:1)
UICollectionViewCell
仅仅是集合视图状态的表示,它不保持集合视图的状态。可以选择屏幕外的项目,在这种情况下甚至不会成为该项目的UICollectionViewCell
实例。
不是直接更新单元格,而是需要告诉集合视图取消选择该项目并让它更新任何屏幕上的单元格。
- (IBAction)clearAction:(UIButton *)sender {
for (NSIndexPath *indexPath in self.buy_code_cv.indexPathForSelectedItems) {
[self.buy_code_cv deselectItemAtIndexPath:indexPath animated:YES];
}
}
答案 1 :(得分:0)
我的建议是在选择任何单元格时维护索引数组。 在这个方法
-(void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.arraySelected containsObject:[NSNumber numberWithInt:indexPath.row]])
{
[self.arraySelected removeObject:[NSNumber numberWithInt:indexPath.row]];
}
else
{
[self.arraySelected addObject:[NSNumber numberWithInt:indexPath.row]];
}
[collectionView reloadData];
}
并且在此方法中编写此代码
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
if ([self.arraySelected containsObject:[NSNumber numberWithInt:indexPath.row]]) {
self.backView.backgroundColor = APP_COLOR;
self.number_label.textColor = [UIColor whiteColor];
self.multiple_label.textColor = [UIColor whiteColor];
}
// uncheck
else {
self.backView.backgroundColor = [UIColor whiteColor];
self.number_label.textColor = HexRGB(0x999999);
self.multiple_label.textColor = HexRGB(0xcccccc);
}
return cell;
}