Change page on UIScrollView

2019-01-21 18:24发布

I have a UIScrollView with 10 pages. I am able to flick between them. I also want to have 2 buttons (a back button and a next button) which when touched will go to the previous or next page. I can't seem to figure out a way to do this though. A lot of my code comes from Apple's page control sample code. Can anybody help?

Thanks

11条回答
Fickle 薄情
2楼-- · 2019-01-21 19:02

Additional to this code that mjdth added, remember to place it in the viewWillAppear or viewDidAppear.

CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * pageNumberYouWantToGoTo;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
查看更多
成全新的幸福
3楼-- · 2019-01-21 19:03

For Swift 3 this is an extension that I find very convenient:

extension UIScrollView {
    func scrollToPage(index: UInt8, animated: Bool, after delay: TimeInterval) {
        let offset: CGPoint = CGPoint(x: CGFloat(index) * frame.size.width, y: 0)
        DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
            self.setContentOffset(offset, animated: animated)
        })
    }
}

And you call it like this:

scrollView.scrollToPage(index: 1, animated: true, after: 0.5)
查看更多
再贱就再见
4楼-- · 2019-01-21 19:06

You can do it this way :

CGRect lastVisibleRect;
CGSize contentSize = [_scrollView contentSize];
lastVisibleRect.size.height = contentSize.height; 
lastVisibleRect.origin.y = 0.0; 
lastVisibleRect.size.width = PAGE_WIDTH; 
lastVisibleRect.origin.x  = contentSize.width - PAGE_WIDTH * (_totalItems - pageIndex); // total item of scrollview and your current page index

[_scrollView scrollRectToVisible:lastVisibleRect animated:NO];
查看更多
对你真心纯属浪费
5楼-- · 2019-01-21 19:08
scroll.contentOffset = CGPointMake(scroll.frame.size.width*pageNo, 0);
查看更多
Emotional °昔
6楼-- · 2019-01-21 19:10

First create a UIScrollView extension like:

extension UIScrollView {

    func setCurrentPage(position: Int) {
        var frame = self.frame;
        frame.origin.x = frame.size.width * CGFloat(position)
        frame.origin.y = 0
        scrollRectToVisible(frame, animated: true)
    }

}

then just call:

self.scrollView.setCurrentPage(position: 2)  // where 2 is your desired page
查看更多
登录 后发表回答