How do you combine UIScrollview with UIPagecontrol to show different views?

僤鯓⒐⒋嵵緔 提交于 2019-12-03 12:39:05

I created this universal solution as examples found was to complicated and this is readable for me, code should be self explanatory.

- (IBAction)changePage:(id)sender {
    _pageControlUsed = YES;
    CGFloat pageWidth = _scrollView.contentSize.width /_pageControl.numberOfPages;
    CGFloat x = _pageControl.currentPage * pageWidth;
    [_scrollView scrollRectToVisible:CGRectMake(x, 0, pageWidth, _scrollView.frame.size.height) animated:YES];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    _pageControlUsed = NO;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (!_pageControlUsed)
            _pageControl.currentPage = lround(_scrollView.contentOffset.x /
            (_scrollView.contentSize.width / _pageControl.numberOfPages));
}

This does the same as @ReneDohan answer without the need for variable to store state

- (IBAction)changePage:(id)sender {
    CGFloat x = self.pageControl.currentPage * self.scrollView.frame.size.width;
    [self.scrollView setContentOffset:CGPointMake(x, 0) animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.isDragging || scrollView.isDecelerating){
        self.pageControl.currentPage = lround(self.scrollView.contentOffset.x / (self.scrollView.contentSize.width / self.pageControl.numberOfPages));
    }
}

Try out this framework : https://github.com/AdrianFlorian/AFImageViewer to present images in a scroll view using a page controll to indicate the current page.

I have't added documentation yet, but you can see examples if you clone the project.

You can easily: - download images from the internet in a separate thread by only giving an array of urls (image urls) - give it an array of UIImage objects - implement a delegate and manage the image for each page yourself

Ricardo Valeriano

There is a related question: How do I use UIPageControl to create multiple views?, a really good way to do that is explained in this blog post: http://cocoawithlove.com/2009/01/multiple-virtual-pages-in-uiscrollview.html.

I've made a demo project for this question. Please visit: https://github.com/lenhhoxung86/PageControlDemo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!