#import <UIKit/UIKit.h> @interface ViewController : UIViewController @end #import "ViewController.h" @interface ViewController ()<UIScrollViewDelegate> @property(nonatomic, strong) NSTimer *timer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIScrollView *sView = [[UIScrollView alloc]initWithFrame:CGRectMake(10, 20, 300, 440)]; sView.contentSize = CGSizeMake(1200, 440); sView.pagingEnabled = YES; sView.showsHorizontalScrollIndicator = NO; sView.tag = 200; //循环创建添加4张图片 for (int i = 0; i < 4; i ++) { UIImageView *imgView = [[UIImageView alloc]init]; imgView.frame = CGRectMake(i*300, 0, 300, 440); imgView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",i]]; [sView addSubview:imgView]; } [self.view addSubview:sView]; //创建书页控件 UIPageControl *pageControl = [[UIPageControl alloc]init]; pageControl.frame = CGRectMake( 100, 440, 120, 20); pageControl.numberOfPages = 4; pageControl.currentPage = 0; pageControl.tag = 100; [self.view addSubview:pageControl]; //设置scrollView的代理为当前类对象 sView.delegate = self; //添加定时器,使用scheuled方法创建的定时器,不需要用fird方法打开(自动开启的) [self addtimer]; } //添加定时器方法 -(void) addtimer{ _timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(nextPage) userInfo:nil repeats:YES]; //返回当前的消息循环对象 [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; } //删除定时器方法 -(void) deleteTimer{ [_timer invalidate]; _timer = nil; } -(void)nextPage{ int page = 0; UIPageControl *pControl = (UIPageControl *)[self.view viewWithTag:100]; if (pControl.currentPage == 3) { page = 0; }else{ page = pControl.currentPage + 1; } //计算滚动的位置 UIScrollView *sView = (UIScrollView *)[self.view viewWithTag:200]; CGFloat offsetX = page * sView.frame.size.width; CGPoint offset = CGPointMake(offsetX, 0); [sView setContentOffset:offset animated:YES]; } #pragma - mark UIScrollViewDelegate //监听滚动的位置,改变pageCotrol的currentPage的值. -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ UIPageControl *pControl = (UIPageControl *)[self.view viewWithTag:100]; CGFloat scrollW = scrollView.frame.size.width; int page = (scrollView.contentOffset.x + scrollW * 0.5 )/ scrollW; pControl.currentPage = page; } -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ [self deleteTimer]; } -(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{ [self addtimer]; } @end
原文:http://my.oschina.net/u/2285956/blog/354917
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!