UICollectionView的scrollToItemAtIndexPath方法不生效

想要实现的效果,就是循环滚动,在拿到数据的时候setModel,reloadData  collectionView然后让其滚动到某个分组

设置collectionView 

//ScreenWidth 屏幕的宽 懒加载设置item的宽高

 UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];

        flow.itemSize = CGSizeMake(ScreenWidth, 200);

        flow.minimumLineSpacing = 0;

        flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;

     _collectionView.pagingEnabled = YES;


1、如果用masonry  设置UICollectionView设置frame

此时你在懒加载collectionView设置了collectionView.pagingEnabled = YES;分页

这时候再调用让他滚到某个分组,会发现不生效

NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:0 inSection:50];

                    [self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];

如果想要它生效可以这样写,就是把pagingEnabled分页放到滚动方法后面

[self.collectionView reloadData]; 

    [self.list_collectionView performBatchUpdates:^{

           

          }completion:^(BOOL finished) {

                //这里获取刷新结束回调

                       NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:0 inSection:50];

                    [self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];

                    self.collectionView.pagingEnabled = YES;

                }

                

        }];

如果还不生效看下 flow.minimumLineSpacing = 0; //是否是0 

//或者这样写

                    //或者用下面的方法替代(或者根据Item大小来自己计算contentOffset)

                   UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:50]];

                  CGFloat _itemSpacing = 0;

                  self.collectionView.contentOffset = CGPointMake(attributes.frame.origin.x - _itemSpacing, 0);


2、 最终发现只有在 masonry 约束的时候有问题,如果collectionView 用frame不会出现此问题,应该是设置了pagingEnabled后在移动的时候系统还没拿到UICollectionView的宽高,因为无法计算

解决办法:

 在[self.collectionView reloadData]之前加上强制view刷新,可以解决此问题

                     [self.view.layer needsLayout];

                     [self.view.layer layoutIfNeeded];


                    

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容