Programmatically Linking UIPageControl to UIScrollView

后端 未结 5 1646
一生所求
一生所求 2020-12-07 13:41

I am making a simple slideshow view within my app. I\'d like to link my UIPageControl to my UIScrollView. This shouldn\'t be too difficult, but I haven\'t been able to fin

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 14:05

    This is actually quite simple to setup. Firstly you need to create the scroll view and page control. Make sure you implement UIScrollViewDelegate in the interface of the class.

        UIScrollView * scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * 3, scrollView.frame.size.height);
        scrollView.delegate = self;
    
        UIPageControl * pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 90, scrollView.frame.size.width, 20)];
        pageControl.numberOfPages = scrollView.contentSize.width/scrollView.frame.size.width;
        [pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
    

    Then you need to add the following two methods:

    - (IBAction)changePage:(id)sender {
        CGFloat x = pageControl.currentPage * scrollView.frame.size.width;
        [scrollView setContentOffset:CGPointMake(x, 0) animated:YES];
    }
    
    -(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView  {
        NSInteger pageNumber = roundf(scrollView.contentOffset.x / (scrollView.frame.size.width));
        pageControl.currentPage = pageNumber;
    }
    

    These methods add the required communication between the page control and the scroll view.

提交回复
热议问题