假设 UIScrollView
有 A,B,C
三个 View 的数据,当给 UIScrollView
赋值数组时,在数组尾部添加第一个元素的拷贝,在开头插入最后一个元素的拷贝,于是原数组变为 C,A,B,C,A
。将 UIScrollView
的初始 contentOffset
设置在新数组的第二个元素 A 上,即C,[A],B,C,A
,在滚动结束时,判断是否达到数组边界,如果到达边界则移动到另外一个相同的元素上。
假设 [] 是当前显示的视图:
C,A,B,[C],A
向右滑动到A
C,A,B,C,[A]
滑动完毕时,将 offset
切换到第二个A视图
C,[A],B,C,A
当继续右滑时
C,A,[B],C,A
这样就有了循环滚动的效果。
首先,UIScrollView
开启翻页
self.pagingEnabled = YES;
修改数据源,初始化 UIImageView
if (_infiniteScrolling && [dataArray count] > 1) {
NSMutableArray *tmpArray = [dataArray mutableCopy];
// 额外拷贝第一个和最后一个数据
[tmpArray addObject:[dataArray firstObject]];
[tmpArray insertObject:[dataArray lastObject] atIndex:0];
_dataArray = [tmpArray copy];
} else {
_dataArray = dataArray;
}
// 创建 UIImageView
CGFloat width = self.frame.size.width;
for (int i = 0; i < _dataArray.count; i ++) {
UIImageView *imageV = [[UIImageView alloc] init];
imageV.frame = CGRectMake(i * width, 0, width, self.frame.size.height);
imageV.contentMode = UIViewContentModeRedraw;
imageV.userInteractionEnabled = YES;
imageV.image = [UIImage imageNamed:_dataArray[i]];
[self addSubview:imageV];
}
self.contentSize = CGSizeMake(_dataArray.count * self.frame.size.width, 0);
// 设置 UIScrollView 的偏移量
self.contentOffset = CGPointMake(width, 0);
调整 offset
和 页码
- (void)makeInfiniteScrolling {
if (!self.infiniteScrolling) {
return;
}
CGFloat width = self.frame.size.width;
NSInteger currentPage = (self.contentOffset.x + width / 2.0) / width;
if (currentPage == self.dataArray.count-1) {
self.currentPage = 0;
[self setContentOffset:CGPointMake(width, 0) animated:NO];
} else if (currentPage == 0) {
self.currentPage = self.dataArray.count - 2;
[self setContentOffset:CGPointMake(width * (self.dataArray.count-2), 0) animated:NO];
} else {
self.currentPage = currentPage-1 ;
}
}
每次 UIScrollView
结束滚动时,作调整
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
[self makeInfiniteScrolling];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
[self makeInfiniteScrolling];
}
实现自动播放,加一个定时器
- (void)startAutoScroll {
if (self.scrollTimer || self.interval == 0 ) {
return;
}
self.scrollTimer = [NSTimer timerWithTimeInterval:self.interval target:self selector:@selector(doScroll) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.scrollTimer forMode:NSDefaultRunLoopMode];
}
- (void)doScroll {
[self setContentOffset:CGPointMake(self.contentOffset.x + self.frame.size.width, 0) animated:YES];
}
如果有滑动操作进行,停止自动播放
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
[self stopAutoScroll];
}
- (void)stopAutoScroll {
[self.scrollTimer invalidate];
self.scrollTimer = nil;
}
停止滑动时,开启自动播放
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
[self startAutoScroll];
}
参考资料:
- UIScrollView with “Circular” scrolling
- WFSBannerScrollView