UICollectionView 无限滑动,类似抖音效果

实现 UICollectionView 的无限滑动效果
首先感谢作者tong-yang提供的文章 https://www.jianshu.com/p/6091c5e37289,写的是swift 版本,我按照参考写了个oc 的

关键代码

滚动到数组源的中心

 [dyCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:imageArrays.count/2 inSection:0]
                             atScrollPosition:UICollectionViewScrollPositionTop
                                     animated:NO]; 

遵守了 《UiScrollViewDelegate》

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 取出当前 滑动视图 当前的坐标
    NSInteger myY = scrollView.contentOffset.y;
    // 根据坐标来判断是在哪一个视图区域
    NSIndexPath *indexNow = [dyCollectionView indexPathForItemAtPoint:CGPointMake(0, myY)];
    // 下标 是最后一个的时候   把视图滚动到 中间 - 1 的位置
    if (indexNow.row == (imageArrays.count -1))
    {
        NSLog(@"往上滑动");
         [dyCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:imageArrays.count/2-1 inSection:0]
                                  atScrollPosition:UICollectionViewScrollPositionTop
                                          animated:NO];
    }
    // 下标是第一个的时候    把视图滚动到 中间的位置 返回到了第一个,下标为 0 的时候
    else if (indexNow.row == 0)
    {
        NSLog(@"往下滑动");
        [dyCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:imageArrays.count/2 inSection:0]
                                 atScrollPosition:UICollectionViewScrollPositionTop
                                         animated:NO];
    }
    // 其他情况显示当前的位置
    else
    {
        [dyCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:indexNow.row inSection:0]
                                 atScrollPosition:UICollectionViewScrollPositionTop
                                         animated:NO];
    }
}

这个原理好似电梯向上运动,而你站在电梯上 往下走,保持原地不动


效果图.gif

代码+图片 密码:gg7i

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

相关阅读更多精彩内容

友情链接更多精彩内容