實現(xiàn)步驟:
1.先整合數(shù)據(jù)源
//循環(huán)滾動,增加尾部和首部的數(shù)據(jù)源用以實現(xiàn)循環(huán)的視覺錯覺
//如原@[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刷新數(shù)據(jù)后再顯示第一個數(shù)據(jù)頁面
[self.collectionView performBatchUpdates:^{
[self.collectionView reloadData];
} completion:^(BOOL finished) {
[self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionLeft];
//開啟滾動計時器
[self startTimer];
}];
2.計時器的設(shè)計
//開啟計時器
- (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.循環(huán)滾動實現(xiàn)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//banner無限循環(huán)快速滑動
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右邊區(qū)域的滑動
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左邊區(qū)域的滑動
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;
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者