解决pageControl页面设置无效问题

 废话不多说,先上代码

1.添加pageViewControl

 1 - (void)addPageControl {
 2     
 3     UIPageControl *pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(100, 100, 130, 15)];
 4     _pageControl = pageControl;
 5     
 6     //设置当前页面和费当前页面的pageControl的圆点颜色
 7     pageControl.pageIndicatorTintColor = [UIColor greenColor];
 8     pageControl.currentPageIndicatorTintColor = [UIColor blueColor];
 9     
10     // 1.设置pageControl单页的时候是否隐藏
11     pageControl.hidesForSinglePage = YES;
12     
13     // 2.设置pageControl显示的图片(KVC)
14     [pageControl setValue:[UIImage imageNamed:@"current"] forKeyPath:@"_currentPageImage"];
15     [pageControl setValue:[UIImage imageNamed:@"other"] forKeyPath:@"_pageImage"];
16     
17     // 3.设置总页数(一定要在初始化UIPageControl对象时设置页数,不然不显示!!!!!!!!!!!!)
18     _pageControl.numberOfPages = self.imageNames.count;
19     
20     [self.view addSubview:pageControl];
21 
22 }

     注意: 一定要在初始化UIPageControl对象时设置页数,不然不显示!

2.添加定时器,定时滚动

 1   #pragma mark - 定时器的相关方法
 2   - (void)startTimer {
 3  
 4      // 返回一个会自动执行任务的定时器
 5      self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextPage:) userInfo:@"123" repeats:YES]; 
 6  
 7      [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
 8 }
 9 
10  - (void)stopTimer {
11  
12      [self.timer invalidate];  
13  
14  }
15  
16   // 滚动到下一页
17  - (void)nextPage:(NSTimer *)timer{
18  
19      // 计算下一页页码
20      NSInteger page = self.pageControl.currentPage + 1;
21  
22      // 超过最后一页
23      if (page == self.imageNames.count) {
24          page = 0;
25      }
26  
27      // 滚动到下一页
28      [_pageScrollView setContentOffset:CGPointMake(page * _pageScrollView.frame.size.width, 0) animated:YES];
29  
30  }

 

3.遵守 UIScrollViewDelegate, 监听滚动的状况, 以便通过crollView.contentOffset.x 来计算页码

 1 #pragma mark - UIScrollViewDelegate
 2 
 3 - (void)scrollViewDidScroll:(UIScrollView *)scrollView{
 4 
 5     // 计算页码
 6     NSUInteger page = (int)(scrollView.contentOffset.x / scrollView.frame.size.width + 0.5); 
 7 
 8     // 设置页码
 9     _pageControl.currentPage = page;
10 
11 }
12 
13 //  用户即将开始拖拽scrollView,停止定时器
14 
15 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
16 
17     [self stopTimer];
18 
19 }
20 
21 //用户已经停止拖拽scrollView,开启定时器
22 
23 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
24 
25     [self startTimer];
26 
27 }

总结:通过以上代码可以看出, 页码的控制是通过 scrollView.contentOffset.x来计算的, 充分借助了 UIScrollViewDelegate中的代理方法, 准确计算位移。

求关注

个人博客:http://www.cnblogs.com/loveDodream-zzt/

Demo:https://github.com/ZTV587/ZTCarouselAD (这个Demo是用XIB搭建的, 纯代码见本文)

 

posted on 2016-11-22 14:57  loveDoDream_zzt  阅读(1285)  评论(0编辑  收藏  举报

导航