實現(xiàn) UICollectionView 的無限滑動效果
首先感謝作者tong-yang提供的文章 http://www.reibang.com/p/6091c5e37289竞漾,寫的是swift 版本眯搭,我按照參考寫了個oc 的
關(guān)鍵代碼
滾動到數(shù)組源的中心
[dyCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:imageArrays.count/2 inSection:0]
atScrollPosition:UICollectionViewScrollPositionTop
animated:NO];
遵守了 《UiScrollViewDelegate》
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
// 取出當前 滑動視圖 當前的坐標
NSInteger myY = scrollView.contentOffset.y;
// 根據(jù)坐標來判斷是在哪一個視圖區(qū)域
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