天天看点

UIPageControl+UIScrollView的简单使用

-、UIPageControl

    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 200, 320, 0)];

    self.pageControl.numberOfPages = 3;   //总页数

    self.pageControl.currentPage = 0;       //当前页

    self.pageControl.hidesForSinglePage = YES;      //单页时隐藏翻页点

    self.pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];      //当前页的颜色

    self.pageControl.pageIndicatorTintColor = [UIColor grayColor];      //非当前页的颜色

    [self.pageControl addTarget:self action:@selector(pageTurn:)          forControlEvents:UIControlEventValueChanged];

    [self.view addSubview:self.pageControl];

- (void)pageTurn:(UIPageControl *)pageControl

{

    NSInteger currentPage = [pageControl currentPage];

}

注意点:

1、page的显示跟高度无关,即使不设置高度也会显示

2、page默认居中显示的,可以手动设置page的位置

3、pageTurn:的调用,

当点击分页的左边时page的currentPage减1,右边加1。pageTurn:的调用跟pageControl的frame有关,高度为0时不会调用到

二、UIPageControl + UIScrollView

使用UIScrollView的时候最好将UIPageControl的高度设为0,否则滑动事件会被UIPageControl截取

- (void)createScrollView {

    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];

    self.scrollView.pagingEnabled = YES;    //允许翻页

    self.scrollView.showsHorizontalScrollIndicator = NO;

    self.scrollView.delegate = self;

    [self.view addSubview:self.scrollView];

    UIView *firstView = [[UIView alloc] initWithFrame:self.view.bounds];

    firstView.backgroundColor = [UIColor redColor];

    UIView *secondView = [[UIView alloc] initWithFrame:CGRectMake(320, 0, self.view.frame.size.width, self.view.frame.size.height)];

    secondView.backgroundColor = [UIColor greenColor];

    UIView *thirdView = [[UIView alloc] initWithFrame:CGRectMake(640, 0,        self.view.frame.size.width, self.view.frame.size.height)];

    thirdView.backgroundColor = [UIColor blackColor];

    [self.scrollView addSubview:firstView];

    [self.scrollView addSubview:secondView];

    [self.scrollView addSubview:thirdView];

    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width*3,   self.scrollView.frame.size.height);

}

实现UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    CGPoint offset = scrollView.contentOffset;

    CGRect bounds = scrollView.frame;

   [self.pageControl setCurrentPage:offset.x / bounds.size.width];  //scrollView翻页刷新pageControl

}