天天看點

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

}