在didSelectItemAtIndexPath中更改UICollectionViewCell的属性

时间:2013-08-07 04:02:56

标签: ios objective-c uicollectionview uicollectionviewcell

我在子类中配置UICollectionViewCell,它将2个子视图添加到contentView属性,两者都是UIImageView,并且两者都将hidden属性设置为{{ 1}}。这些子视图是“已选中”和“未选中”的图像,它们覆盖单元格中的主要UIImageView,以指示是否使用UICollectionView的“多选”功能选择当前单元格。

当点击单元格时,在委托上调用YES,我想在“已检查”的UIImageView上collectionView:didSelectItemAtIndexPath:。在单元格上调用它什么都不做 - 单元格似乎被锁定在最初绘制的状态。

是否可以对setHidden:NO之外的单元格进行更改?我尝试在collectionView:cellForItemAtIndexPath:内手动添加子视图,但它只是对UI完全没有任何更改。我已经验证了委托方法被调用,它只是没有让我的单元格改变。

collectionView:didSelectItemAtIndexPath:

1 个答案:

答案 0 :(得分:4)

您尝试这样做的方式不正确。您需要保留对属性中所选单元格的引用。在此示例中,我使用数组来保存所选单元格的索引路径,然后检查传入cellForItemAtIndexPath的索引路径是否包含在该数组中。如果您单击已选择的单元格,则取消选择该单元格:

@interface ViewController ()
@property (strong,nonatomic) NSArray *theData;
@property (strong,nonatomic) NSMutableArray *paths;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.paths = [NSMutableArray new];
    self.theData = @[@"One",@"Two",@"Three",@"Four",@"Five",@"Six",@"Seven",@"Eight"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"CVCell" bundle:nil] forCellWithReuseIdentifier:@"cvCell"];

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    [self.collectionView setCollectionViewLayout:flowLayout];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.theData.count;
}

-(CVCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cvCell";
    CVCell *cell = (CVCell *) [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.label.text = self.theData[indexPath.row];
    if ([self.paths containsObject:indexPath]) {
        [cell.iv setHidden:NO]; // iv is an IBOutlet to an image view in the custom cell
    }else{
        [cell.iv setHidden:YES];
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.paths containsObject:indexPath]) {
        [self.paths removeObject:indexPath];
    }else{
        [self.paths addObject:indexPath];
    }

    [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

        return CGSizeMake(150, 150);
}