UICollectionView reload data Issue

China☆狼群 提交于 2019-12-01 20:11:18

You add a new label each time you tap the reload button. You should add the label once and change the label text according.

Here a simple example.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    MyCell *cell = (MyCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell"
                                                                               forIndexPath:indexPath];
    [cell setMyTextLabel:indexPath.row];
    return cell;
}

where MyCell will contains a UILabel and a property to modify its text.

I really suggest to take a look at Fun with UICollectionView code by @Ben Scheirman.

Hope that helps.

P.S. Rename myCell to MyCell. A class should start with an uppercase letter.

You are adding your label when you tap reload button. In that case you are adding label again and again...

So there are three solutions:

  • Make your cell reusable
  • Remove your cell from superview in reload method.
  • You can check if label's text length is not equal to zero. In that case no need to add that label and change text.
Raja
 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
 {
       UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
dispatch_async(dispatch_get_main_queue(), ^{

  //  ********* Changed *******

        for (UIView *v in [cell.contentView subviews])
        [v removeFromSuperview];

 // ********** Changed **********
            if ([self.collectionviewFlow.indexPathsForVisibleItems containsObject:indexPath]) {
            NSString *img_name=[NSString stringWithFormat:@"%@_thumb%d.png",self.VaritiesName,(int)indexPath.row+1];
            imageVw=[[UIImageView alloc]initWithImage:[UIImage imageNamed: img_name]];
            imageVw.frame=CGRectMake(10,10,100,100);
            [cell.contentView addSubview:imageVw];
            }
       });
     cell.backgroundColor=[UIColor clearColor];
     return cell;
}

It is quit late, but here is my solution.

if you used custom collectionviewcell try to use 'func prepareForReuse()'

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!