3

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

当点击单元格时,collectionView:didSelectItemAtIndexPath:会在委托上调用,我想setHidden:NO在“已检查”的 UIImageView 上调用。在单元格上调用它根本没有任何作用——单元格似乎被锁定在其最初绘制的状态。

是否可以更改外部单元格collectionView:cellForItemAtIndexPath:?我已经尝试在 中手动添加子视图collectionView:didSelectItemAtIndexPath:,但它对 UI 没有任何改变。我已经验证了委托方法被调用了,它只是没有让我的单元格发生变化。

- (void) collectionView(UICollectionView *)cv didSelectItemAtIndexPath(NSIndexPath *)indexPath {
    ShotCell *cell = [self collectionView:cv cellForItemAtIndexPath:indexPath];
    UILabel *testLabel = UILabel.alloc.init;
    testLabel.text = @"FooBar";
    testLabel.sizeToFit;
    [cell.contentView.addSubview testLabel];
}
4

1 回答 1

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);
}
于 2013-08-07T06:48:16.843 回答