iOS使用collectionView实现无限轮播
自己封装了一个无限轮播功能,与大家一起分享. 有bug欢迎指正.
主要代码:
设置collectionView有几组:
#define kMaxSection 100 //设置一个比较大的分区值
初始化定时器
- (void)startTimer
{
self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
定时器执行方法
- (void)nextPage
{
//1 获取当前正在展示的位置
NSIndexPath *currentIndexPath =[self.collectionView.indexPathsForVisibleItems lastObject];
//核心代码: !!!马上显示回最中间那组的数据!!!
NSIndexPath *midIndexPath =[NSIndexPath indexPathForItem:currentIndexPath.item inSection:kMaxSection/2];
[self.collectionView scrollToItemAtIndexPath:midIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
//核心代码: 2 计算出下一个需要展示的位置
NSInteger nextItem = midIndexPath.item + 1;
NSInteger nextSection = midIndexPath.section;
if (nextItem == self.imageArray.count) {
nextItem = 0;
nextSection++;
}
//3 通过动画滚动到下一个位置
NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
[self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:(UICollectionViewScrollPositionLeft) animated:YES];
}
销毁定时器
- (void)endTimer
{
[self.timer invalidate];
self.timer = nil;
}
collectionView代理方法:
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 0;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(collectionView.frame.size.width, collectionView.frame.size.height);
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return kMaxSection;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.imageArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
LoopCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
cell.imageStr = self.imageArray[indexPath.item];
return cell;
}
scrollView代理方法:
//手开始拖动时停止自动滚动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[self endTimer];
}
//手离开时继续自动滚动
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
[self startTimer];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//页码
self.pageControl.currentPage = (int)(scrollView.contentOffset.x / scrollView.frame.size.width + 0.5) % self.imageArray.count;
}
原理就是初始化collectionView有很多分组,当滚动到本组最后一个时,继续向下一组滚动. 定时滚动时每次重置到中间位置.