Reputation: 7022
I have a custom UICollectionViewCell
that contains a BOOL value called isOnSale. I set this value in - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
. A label is added to the cell if the isOnSale
is true. This works perfectly, however if I scroll down and then scroll back up the labels have swapped to the cell next in the index. I scroll up, and back down, they are back to there original places. I am guessing it is a layout problem but I have spent the last hour or so trying to spot the bug, while implementing other examples here.
Here is my 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
If the item is on sale then layoutSubViews
updates the view and adds the Sale
label to the cell.
Here is my 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;
}
The problem is that the Sale label is moving when the cells leave the screen. Its strange, because the self.bgImageView
shows the correct content.
If anything is unclear please ask.
Upvotes: 2
Views: 10259
Reputation: 2501
remove your label from the superview in either layoutSubviews
's else
branch or in -prepareForResuse
method
Upvotes: 1