Change page on UIScrollView

IphoneUiscrollview

Iphone Problem Overview


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

Iphone Solutions


Solution 1 - Iphone

You just tell the buttons to scroll to the page's location:

CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * pageNumberYouWantToGoTo;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];

Solution 2 - Iphone

Here is an implementation for Swift 4:

func scrollToPage(page: Int, animated: Bool) {
    var frame: CGRect = self.scrollView.frame
    frame.origin.x = frame.size.width * CGFloat(page)
    frame.origin.y = 0
    self.scrollView.scrollRectToVisible(frame, animated: animated)
}

and is easily invoked by calling:

self.scrollToPage(1, animated: true)

Edit:

A nicer way of doing this is to support both horizontal and vertical pagination. Here is a convenient extension for that:

extension UIScrollView {

    func scrollTo(horizontalPage: Int? = 0, verticalPage: Int? = 0, animated: Bool? = true) {
        var frame: CGRect = self.frame
        frame.origin.x = frame.size.width * CGFloat(horizontalPage ?? 0)
        frame.origin.y = frame.size.width * CGFloat(verticalPage ?? 0)
        self.scrollRectToVisible(frame, animated: animated ?? true)
    }

}

This creates an extension on UIScrollView where you can scroll to any page, vertical or horisontal.

self.scrollView.scrollTo(horizontalPage: 0)
self.scrollView.scrollTo(verticalPage: 2, animated: true)
self.scrollView.scrollTo(horizontalPage: 1, verticalPage: 2, animated: true)

Solution 3 - Iphone

scroll.contentOffset = CGPointMake(scroll.frame.size.width*pageNo, 0);

Solution 4 - Iphone

scrollRectToVisible was not working for me, so I had to animate the contentOffset. This code works in swift 3.

func scrollToPage(_ page: Int) {
    UIView.animate(withDuration: 0.3) { 
        self.scrollView.contentOffset.x = self.scrollView.frame.width * CGFloat(page)
    }
}

Solution 5 - Iphone

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)

Solution 6 - Iphone

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];

Solution 7 - Iphone

Here is a static method in swift:

static func scrollToPage(scrollView: UIScrollView, page: Int, animated: Bool) {
    var frame: CGRect = scrollView.frame
    frame.origin.x = frame.size.width * CGFloat(page);
    frame.origin.y = 0;
    scrollView.scrollRectToVisible(frame, animated: animated)
}

Solution 8 - Iphone

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

Solution 9 - Iphone

If scrollRectToVisible doesn't work try this :

let frame = scrollView.frame
    let offset:CGPoint = CGPoint(x: CGFloat(sender.currentPage) * frame.size.width, y: 0)
    self.scrollView.setContentOffset(offset, animated: true)

Solution 10 - Iphone

I wanted to implement an image slider with automatic scrolling using a UIScrollView and a UIStackView. This is what I ended up with and it's working pretty well. I a using PureLayout for AutoLayout:

class ImageSlideShow: UIView {

private let scrollView = UIScrollView()
private var images: [UIImage] = []
private var scrollTimer: Timer?

init() {
    super.init(frame: .zero)
    self.setupView()
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

public func setImages(_ images: [UIImage], initialIndex: Int = 0) {
    self.images = images
    self.scrollTimer?.invalidate()
    self.scrollView.removeAllSubviews()
    
    let stackView = self.getStackView()
    self.scrollView.addSubview(stackView)
    
    stackView.autoMatch(.height, to: .height, of: self.scrollView)
    stackView.autoPinEdgesToSuperviewEdges()
    
    self.images.forEach { image in
        let imageView = UIImageView(image: image)
        imageView.contentMode = .scaleAspectFill
        stackView.addArrangedSubview(imageView)
        imageView.autoMatch(.width, to: .width, of: self.scrollView)
    }
    
    self.setupScrollTimer()
}

private func getStackView() -> UIStackView {
    let stackView = UIStackView()
    stackView.axis = .horizontal
    stackView.alignment = .fill
    stackView.distribution = .equalSpacing
    stackView.spacing = 0
    return stackView
}

private func setupScrollTimer() {
    self.scrollTimer = Timer.scheduledTimer(
        timeInterval: 0.5,
        target: self,
        selector: #selector(scroll), userInfo: nil,
        repeats: true
    )
}

@objc private func scroll() {
    let currentPage = self.scrollView.contentOffset.x / scrollView.frame.size.width
    var nextPage = currentPage + 1
    
    var frame: CGRect = self.scrollView.frame
    
    if nextPage >= CGFloat(self.images.count) {
        nextPage = 0
    }
    
    frame.origin.x = frame.size.width * CGFloat(nextPage)
    self.scrollView.scrollRectToVisible(frame, animated: true)
}

private func setupView() {
    self.backgroundColor = Colors.cream
    self.setupScrollView()
}

private func setupScrollView() {
    self.addSubview(self.scrollView)
    self.scrollView.autoPinEdgesToSuperviewEdges(with: .margin(Metrics.paddingDoublePlus))
    self.scrollView.isPagingEnabled = true
    self.scrollView.layer.cornerRadius = Metrics.cornerRadius
    self.scrollView.showsHorizontalScrollIndicator = false
    self.scrollView.showsVerticalScrollIndicator = false
}

}

Solution 11 - Iphone

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];

Solution 12 - Iphone

Swift Solution

func changePage(pageControl: UIPageControl) {

    let page = CGFloat(pageControl.currentPage)
    var frame = self.scrollView.frame
    frame.origin.x = frame.size.width * page
    frame.origin.y = 0
    self.scrollView.scrollRectToVisible(frame, animated: true)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjohnView Question on Stackoverflow
Solution 1 - IphonemjdthView Answer on Stackoverflow
Solution 2 - IphonePontusView Answer on Stackoverflow
Solution 3 - IphoneMr.Guru.PatelView Answer on Stackoverflow
Solution 4 - IphoneChuy47View Answer on Stackoverflow
Solution 5 - IphoneDavid H.View Answer on Stackoverflow
Solution 6 - IphoneHSGView Answer on Stackoverflow
Solution 7 - IphoneMax HudsonView Answer on Stackoverflow
Solution 8 - IphoneZahidur Rahman FaisalView Answer on Stackoverflow
Solution 9 - IphonegiLisHView Answer on Stackoverflow
Solution 10 - IphoneShacharView Answer on Stackoverflow
Solution 11 - IphoneJuan ReyesView Answer on Stackoverflow
Solution 12 - IphoneSazzad Hissain KhanView Answer on Stackoverflow