当我们使用UICollectionView实现,无线轮播滚动时(整页滚动。可视区域只会显示一个item), 采用多个分区的形式, 每次滚动完之后,会无动画滚动到中间的分区,这样就实现了无线滚动的效果。

通过UIScrollView的-scrollViewDidEndDecelerating:方法得到indexPath更新的时刻, 然后用[collectionView indexPathsForVisibleItems]获取一组当前显示的cell们的indexPath的数组,和上面的方案一样,我只要取里面的第一个.

当我们采用上面两种方式,回去当前的显示cell或则indexPath时, 在我们快速手动滚动的时候, 虽然在视觉上看到只显示一个item, 但是实际上有时候我们获取是多个cell或则indexPath的情况,并且顺序是不一定的, 导致我们通过firstobject或则lastobject的方式获取的item可能是错误的, 导致滚动顺序错乱。注意:对获取之后的数组进行排序也是不可取的, 也会造成顺序错乱

解决方法:

// 监听UIScrollView的滑动停止

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

// UICollectionView的宽度和Cell宽度相等: 当手指快读滑动时, 有时indexPathsForVisibleItems() 获取的indexPath不一定只有一个cell,有时候会出现两个,而且顺序不一定正确。

NSIndexPath *currentIndexPath = [self.videoCollectionView indexPathForItemAtPoint:self.videoCollectionView.contentOffset];

if (currentIndexPath && currentIndexPath.row < self.datas.count) {

NSIndexPath *currentIndexPathReset = [NSIndexPath indexPathForItem:currentIndexPath.row inSection:maxSection / 2];

[self.videoCollectionView scrollToItemAtIndexPath:currentIndexPathReset atScrollPosition:UICollectionViewScrollPositionNone animated:NO];

self.pageControl.currentIndex = currentIndexPathReset.row;

}

}

我们这里可以通过方法:- (nullable NSIndexPath *)indexPathForItemAtPoint:(CGPoint)point; 通过指定坐标来获取当前正在显示的cell,该方法可以获取正在显示的item的NSIndexPath, 得到正确的下标。

推荐链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: