UICollectionView的scrollToItemAtI
想要实现的效果,就是循环滚动,在拿到数据的时候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];