Reputation: 47
Basically, I have a UICollectionViewCell that loads values from the datasource an in addition it is supposed to set the height of a subview frame to be equal to one of the values in the datasource.
The problem I am having is that it looks correct when I first run the project, but when I scroll a few times back and forth, as cells are being reused, the text values stay the same but the frame of the subview changes.
What confuses me is that the variable that is setting the text in a label in the cell is the same variable that is setting the height value for the subview in the same cell; but the label text is always correct, yet the height of the UIView frame constantly changes with scrolling.
I know it's probably something to do with how cells are being reused, but I can't put my finger on it.
Below is my code for the cellForRowAtIndexPath. Thanks!
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
DailyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DayCell" forIndexPath:indexPath];
cell.backgroundContainerView.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.3f];
float total = [[dummyData objectAtIndex:indexPath.row][@"total"] floatValue] * 2;
UIView * backgroundFillView = [UIView new];
if (![cell viewWithTag:1000]) {
NSLog(@"Creating backgroundFillView on Cell: %ld", (long)indexPath.row);
backgroundFillView.tag = 1000;
[cell.backgroundContainerView addSubview:backgroundFillView];
}
cell.debugCellNumber.text = [NSString stringWithFormat:@"%ld", (long)indexPath.row];
cell.debugCellTotal.text = [NSString stringWithFormat:@"%f", total];
backgroundFillView.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.5f];
backgroundFillView.frame = CGRectMake(0, 200 - total, 60, total);
NSLog(@"Cell: %ld, total: %f", (long)indexPath.row, total);
NSLog(@"Cell: %ld, backgroundFillView Height: %f", indexPath.row, backgroundFillView.frame.size.height);
NSLog(@"Cell: %ld, backgroundFillView Y: %f", indexPath.row, backgroundFillView.frame.origin.y);
return cell;
}
Upvotes: 0
Views: 2381
Reputation: 8628
You only add a backgroundFillView
the first time you populate a cell. Not when it is re-used.
Replace:
UIView * backgroundFillView = [UIView new];
if (![cell viewWithTag:1000]) {
NSLog(@"Creating backgroundFillView on Cell: %ld", (long)indexPath.row);
backgroundFillView.tag = 1000;
[cell.backgroundContainerView addSubview:backgroundFillView];
}
with:
UIView * backgroundFillView = [cell viewWithTag:1000];
if (! backgroundFillView) {
NSLog(@"Creating backgroundFillView on Cell: %ld", (long)indexPath.row);
backgroundFillView = [UIView new];
backgroundFillView.tag = 1000;
[cell.backgroundContainerView addSubview:backgroundFillView];
}
Upvotes: 1