import "ViewController.h" #define allPages 4 @interface ViewController ()<UIScrollViewDelegate> {UIScrollView *myScrollView;UIPageControl *pageControl;NSTimer timer; } @end @implementation ViewController - (void)viewDidLoad {[super viewDidLoad];myScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 200, 414, 300)];myScrollView.contentSize = CGSizeMake(4144, 300);myScrollView.backgroundColor = [UIColor whiteColor];myScrollView.pagingEnabled = YES;myScrollView.delegate = self;[self.view addSubview:myScrollView];for (int index = 0; index<allPages; index++) { UIImageView imageView = [[UIImageView alloc]initWithFrame:CGRectMake(414index, 0, 414, 300)]; imageView.image = [UIImage imageNamed:[[NSString alloc]initWithFormat:@"%d.JPG",index+1]]; [myScrollView addSubview:imageView];}pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 480, 414, 20)];pageControl.numberOfPages = 4;pageControl.tag = 101;pageControl.backgroundColor = [UIColor clearColor];//设置页码点的颜色pageControl.pageIndicatorTintColor = [UIColor grayColor];//设置选中页码点的颜色pageControl.currentPageIndicatorTintColor = [UIColor redColor];[pageControl sizeForNumberOfPages:2];[self.view addSubview:pageControl];[self addTimer];} #pragma mark 自定义方法 - (void)addTimer{//创建定时器,并是nextImage循环执行 timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(nextImage) userInfo:self repeats:YES]; } - (void)nextImage{ NSInteger page = 0;//判断是否为最后一页,如果是最后一页调转到第一页;否则调到下一页 if (pageControl.currentPage != allPages-1) { page = pageControl.currentPage + 1; }NSLog(@"%ld",page);CGPoint point = CGPointMake(myScrollView.frame.size.width * page, 0);//设置偏移量[myScrollView setContentOffset:point animated:YES];//创建线程NSRunLoop,监听timer[[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode]; } - (void)stopTimer{ //销毁定时器 [timer invalidate]; }
pragma mark 系统代理方法
//开始滑动时,调到下一个页面;是页码移动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{ int page = (scrollView.contentOffset.x)/scrollView.frame.size.width; pageControl.currentPage = page; }
//开始拖动时销毁定时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ [self stopTimer];}
//拖动结束时销创建时器
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ [self addTimer]; }
@end
文/狼之神(简书作者)原文链接:http://www.jianshu.com/p/01f44685fc04著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。