滚动后,自定义UICollectionView单元格layoutsubview不正确

时间:2014-07-03 17:15:47

标签: ios uicollectionview

我有一个自定义UICollectionViewCell,其中包含一个名为isOnSale的BOOL值。我在- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath中设置了这个值。如果isOnSale为真,则会向单元格添加标签。这非常有效,但是如果我向下滚动然后向上滚动标签已经交换到索引中的下一个单元格。我向上滚动,然后退回,他们回到原来的地方。我猜这是一个布局问题,但我花了最后一个小时左右尝试发现错误,同时在这里实现其他示例。

这是我的UICollectionViewCell

@implementation SaleCollectionViewCell


- (id)initWithFrame:(CGRect)frame
    {
       self = [super initWithFrame:frame];
     if (self) {
        // Initialization code
        self.bgImageView = [[UIImageView alloc] init];
        self.sale = [[UILabel alloc] init];
        self.bgImageView.image = [UIImage imageNamed:@"iron1"];

        [self.contentView insertSubview:self.bgImageView atIndex:0];

        self.layer.cornerRadius = 6.0;

    }
    return self;
}

-(void)layoutSubviews{

    [super layoutSubviews];

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

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

    }
    else{
        NSLog(@"Is not on sale");
        self.bgImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);


    }

}
@end

如果商品有售,则layoutSubViews会更新视图并将Sale标签添加到单元格中。

这是我的UICollectionView - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SaleCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    cell.clipsToBounds = YES;

    SaleImage * saleImage = [self.saleObjs objectAtIndex:indexPath.row];
    cell.bgImageView.image = [UIImage imageNamed:saleImage.imageName];
    if (saleImage.isOnSale) {
        cell.isOnSale = YES;
    }
    else{
        cell.isOnSale=NO;
    }

    return cell;

}

问题是,当细胞离开屏幕时,Sale标签正在移动。很奇怪,因为self.bgImageView显示正确的内容。

如果有任何不清楚的地方,请询问。

1 个答案:

答案 0 :(得分:1)

layoutSubviews的{​​{1}}分支或else方法

中的超级视图中删除您的标签
相关问题