- (void)viewDidLoad {
//创建一个scrollview
self.scrollView = [[UIScrollView alloc ] initWithFrame:[UIScreen mainScreen].bounds];
//设置偏移量
self.scrollView.contentOffset = CGPointMake(0, 0);
self.scrollView.contentSize = CGSizeMake(5 * kWidth, 0);
//设置代理
self.scrollView.delegate = self;
self.scrollView.showsHorizontalScrollIndicator = NO;
[self.view addSubview:_scrollView];
//创建5个label
for (int i = 0; i < 5; i ++) {
self.label = [[UILabel alloc] initWithFrame:CGRectMake(kWidth * i, 0, kWidth, 667)];
self.label.text = [NSString stringWithFormat:@"%d", i];
self.label.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1.0];
self.label.font = [UIFont boldSystemFontOfSize:30];
self.label.textAlignment = NSTextAlignmentCenter;
[self.scrollView addSubview:self.label];
}
// 创建一个UIPageControl
self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(30, self.scrollView.frame.size.height - 40, 100, 20)];
self.pageControl.pageIndicatorTintColor = [UIColor redColor];
self.pageControl.currentPageIndicatorTintColor = [UIColor grayColor];
self.pageControl.currentPage = 0;
// 设置一共页数
self.pageControl.numberOfPages = 5;
[self.view addSubview:self.pageControl];
self.scrollView.pagingEnabled = YES;
[self addTimer];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
//实现定时器的方法
- (void)nextLabel{
//增加pageControl的页码
NSInteger page = 0;
if (self.pageControl.currentPage == 4) {
page = 0;
}else{
page = self.pageControl.currentPage + 1;
}
//计算scrollview滚动的位置
CGFloat offsetX = page * self.scrollView.frame.size.width;
CGPoint offset = CGPointMake(offsetX, 0);
[self.scrollView setContentOffset:offset animated:YES];
}
//封装一个添加定时器的方法
- (void)addTimer{
self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextLabel) userInfo:nil repeats:YES];
//多线程的优先级
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
//正在滚动的时候
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//根据scrollview的滚动位置决定pagecontrol显示第几页
NSInteger page = self.scrollView.contentOffset.x / self.scrollView.frame.size.width;
self.pageControl.currentPage = page;
}
//开始拖拽的时候调用
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
//停止定时器
[self.timer invalidate];
//定时器只能只用一次,一旦停止了 只能清空
self.timer = nil;
}
//停止拖拽
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
[self addTimer];
}