具有动态单元格内容的UICollectionView - 让单元格记住状态

Dev*_*evC 4 ios uicollectionview

我有一个UICollectionView包含动态内容.我遇到的问题是当细胞dequeued忘记它的状态时.在我的- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath我有一个布尔值,当它为真时,它会变为真实的图像,但是当它为假时,它会变为假图像.然而,当我向下滚动并向后滚动时,细胞会忘记那里的状态.有没有办法让细胞记住它的状态?这就是我的内心

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath   

    SalesCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    SaleImage * saleImage = [self.SaleObjs objectAtIndex:indexPath.row];
    cell.bgImageView.image = [UIImage imageNamed:saleImage.imageName];
    if (saleImage.isBookable) {
        cell.isBookable = YES;
    }
    else{
        cell.isBookable=NO;
    }

return cell;
}
Run Code Online (Sandbox Code Playgroud)

我有一个补救措施,但它会影响性能.我把它添加到我的自定义单元格中;

-(void)prepareForReuse{
    [super prepareForReuse];


    [self setNeedsLayout];
}
Run Code Online (Sandbox Code Playgroud)

这是我的集合视图单元格;

@implementation SalesCollectionViewCell


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        // Initialization code
        self.layer.cornerRadius = 6.0;
        self.bgImageView = [[UIImageView alloc] init];
        self.book = [[UILabel alloc] init];      
        [self.contentView insertSubview:self.bgImageView atIndex:0];


         return self;
}

-(void)layoutSubviews{

    [super layoutSubviews];

    if (self.isBookable) {
        self.book.frame =CGRectMake(0, self.bounds.size.height - 41, 140, 41);
        self.book.text = @"Book this Item";
        self.book.textColor = [UIColor whiteColor];
        self.book.adjustsFontSizeToFitWidth=YES;
        self.book.textAlignment = NSTextAlignmentCenter;
        self.book.backgroundColor= [UIColor darkGrayColor];
        self.book.font = [UIFont fontWithName:kAppFont size:17.0];
        [self.contentView insertSubview:self.book atIndex:2];

        self.bgImageView.frame =CGRectMake(0, 0, 140, self.bounds.size.height - self.book.bounds.size.height);


    }
    else{
        self.bgImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);

    }



}

-(void)prepareForReuse{
    [super prepareForReuse];

    [self.book removeFromSuperview];
    [self setNeedsLayout];


}
Run Code Online (Sandbox Code Playgroud)

Leo*_*ica 5

细胞不应该"记住"它们的状态; 集合视图或表视图数据源应该.在相应的cellForIndexPath方法中,您应该设置单元的当前状态,并让它根据需要进行自我配置.