簡體   English   中英

滾動后,自定義UICollectionView單元格layoutsubview不正確

[英]Custom UICollectionView cells layoutsubview is incorrect after scrolling

我有一個自定義UICollectionViewCell ,其中包含一個名為isOnSale的BOOL值。 我在- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath設置此值。 如果isOnSale為true, 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;

}

問題是當單元格離開屏幕時,銷售標簽正在移動。 這很奇怪,因為self.bgImageView顯示正確的內容。

如果不清楚,請詢問。

layoutSubviewselse分支或-prepareForResuse方法中從-prepareForResuse視圖中刪除標簽

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM