实现步骤:
1.先整合数据源
//循环滚动,增加尾部和首部的数据源用以实现循环的视觉错觉
//如原@[a,b,c],整合成@[c,a,b,c,a]
self.lastX = 0;
NSMutableArray *tmpArray = [NSMutableArray arrayWithArray:URLArray];
[tmpArray addObject:[URLArray firstObject]];
[tmpArray insertObject:[URLArray lastObject] atIndex:0];
self.urlArray = [NSArray arrayWithArray:tmpArray];
[self.collectionView reloadData];
//collectionView刷新数据后再显示第一个数据页面
[self.collectionView performBatchUpdates:^{
[self.collectionView reloadData];
} completion:^(BOOL finished) {
[self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionLeft];
//开启滚动计时器
[self startTimer];
}];
2.计时器的设计
//开启计时器
- (void)startTimer {
[self stopTimer];
self.timer = [MSWeakTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(scrollToNextPage) userInfo:nil repeats:YES dispatchQueue:dispatch_get_main_queue()];
}
//collectionView滚动至下一页
- (void)scrollToNextPage {
NSIndexPath *indexpath = [self.collectionView indexPathForItemAtPoint:self.collectionView.contentOffset];
NSIndexPath *incrementPath = nil;
if (indexpath.item == [self.collectionView numberOfItemsInSection:0] - 1) {
//滚动至尾部
incrementPath = [NSIndexPath indexPathForItem:0 inSection:0];
} else if ([self.collectionView numberOfItemsInSection:0] == 0) {
//滚动至首部
incrementPath = [NSIndexPath indexPathForItem:0 inSection:0];
} else {
//中间部分滚动
incrementPath = [NSIndexPath indexPathForItem:indexpath.item + 1 inSection:0];
}
[self.collectionView scrollToItemAtIndexPath:incrementPath atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
}
3.循环滚动实现
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//banner无限循环快速滑动
CGFloat currX = scrollView.contentOffset.x;
CGFloat pageX = currX - scrollView.frame.size.width;
NSInteger currCount = self.urlArray.count;
if (currCount > 1) {
if ((currX - _lastX) >= 0) {
//Banner右边区域的滑动
if(currX > (currCount-2)*scrollView.frame.size.width){
_lastX = 0;
[scrollView setContentOffset:CGPointMake(currX-(currCount-2)*scrollView.frame.size.width, 0)];
}
//pageVC滑动
if (currX < scrollView.frame.size.width) {
pageX = (currCount-2)*scrollView.frame.size.width;
}
}else{
//Banner左边区域的滑动
if(currX > (currCount-2)*scrollView.frame.size.width){
_lastX = 0;
[scrollView setContentOffset:CGPointMake(currX-(currCount-2)*scrollView.frame.size.width, 0)];
}else if (currX < scrollView.frame.size.width) {
_lastX = currCount*scrollView.frame.size.width;
[scrollView setContentOffset:CGPointMake(currX+(currCount-2)*scrollView.frame.size.width, 0)];
}
//pageVC滑动
if (currX < scrollView.frame.size.width) {
pageX = (currCount-2)*scrollView.frame.size.width;
}else if (currX > (currCount-2)*scrollView.frame.size.width){
pageX = 0;
}
}
int currPage = (int)(pageX/scrollView.frame.size.width);
self.pageControl.currentPage = currPage;
}
}
网友评论