地址:github.com/junjiewang1111/unlimitedUIImageView
首先,创建轮播器的视图:
JJCycleView*cycleView = [[JJCycleView alloc] initWithFrame:CGRectMake(0, 20,self.view.bounds.size.width, 200)];
本地图片资源获取:
NSMutableArray*imageURLs = [NSMutableArray array];
for(inti = 0; i<5 ; i++) {
NSString*imageName = [NSString stringWithFormat:@"Home_Scroll_%02d.jpg",i+1];
NSURL*url = [[NSBundle mainBundle]URLForResource:imageName withExtension:nil];
[imageURLs addObject:url];
}
self.cycleView.imageURLs= imageURLs;
JJCycleView使用UICollectionView,实现数据源方法,完成数据的传递都是比较简单的.轮播器的播放,需要计算contentOffset.x,根据偏移量计算是第几页.
- (void)scrollViewDidScroll:(UIScrollView*)scrollView{
//获取偏移量
CGFloatoffsetX = scrollView.contentOffset.x;
//计算页数
NSIntegerpage = (offsetX +self.bounds.size.width* .5)/self.bounds.size.width;
self.pageControl.currentPage= page %self.imageURLs.count;
}
轮播器的滚动分自动和手动,手动时需要暂停NSTimer计时器,当手动拖动完成时,就需要重新开启,当然,计时器需要加入到RunLoop
- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView{
self.timer.fireDate= [NSDate distantFuture];
}
//计时器开启
- (void)scrollViewDidEndDragging:(UIScrollView*)scrollView willDecelerate:(BOOL)decelerate{
self.timer.fireDate= [NSDate dateWithTimeIntervalSinceNow:1.5];
}
[[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
不是手动拖拽就调用下面方法实现自动播放
//手动滑动完成时调用
- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView{
//获取偏移量
CGFloatoffsetX = scrollView.contentOffset.x;
//计算页数
NSIntegerpage = offsetX /self.bounds.size.width;
NSIntegercellCount = [self.collectionView numberOfItemsInSection:0];
if(page == 0) {
self.collectionView.contentOffset=CGPointMake(offsetX +self.imageURLs.count*self.bounds.size.width*kseed, 0);
}elseif(page == cellCount - 1){
self.collectionView.contentOffset=CGPointMake(offsetX -self.imageURLs.count*self.bounds.size.width*kseed, 0);}
}
一个小demo,谢谢!
网友评论