Question

Following code is a very simple program which is used to display numbers from 1-10000 in the UICollectionView. It is displaying correctly without scrolling, but the cells are overlapped if you scroll down and scroll back the collection view.

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 10000;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(100,30);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = @"cell_id";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    [label setText:[NSString stringWithFormat:@"%d", indexPath.item, nil]];
    [cell.contentView addSubview:label];

    return cell;
}
Was it helpful?

Solution

The problem here is that the label is being added to the view's cell repeatedly. The old label is not removed when the cell is reused and hence you see multiple numbers overlapped. the solution can be to remove the old label like this

for (UIView *view in cell.contentView.subviews) {
        if ([view isKindOfClass:[UILabel class]]) {
            [view removeFromSuperview];
        }
    }

before adding to the cell. However this will create performance problems when the number of subviews increase. You can create a custom cell with a label and then update its value. I haven't tried it but i believe it will work. Hope this helps

OTHER TIPS

This worked for me in Swift 3: Almost same solution as approved solution, note that I used

cell.subViews 

instead of

cell.contentView.subViews

What's worked for me is:

for view in cell.subviews {
  view.removeFromSuperview()
}

Set the cell layer anchorPointZ to row index in cellForItemAtIndexPath: method

cell.layer.anchorPointZ = CGFloat(indexPath.row)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top