Create a loop on UIScrollView

2019-09-07 04:05发布

问题:

I can scroll back and forth on the views but I can't loop the views so it scrolls back when I'm on ViewController3 and forward on ViewController1 to create a loop. How would I do this?

The code below is what I've done so far.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()

    let vc0 = ViewController0(nibName: "ViewController0", bundle: nil)

    var frame0 = vc0.view.frame
    frame0.origin.x = self.view.frame.size.width
    vc0.view.frame = frame0

    self.addChildViewController(vc0)
    self.scrollView.addSubview(vc0.view)
    vc0.didMove(toParentViewController: self)

    let vc1 = ViewController1(nibName: "ViewController1", bundle: nil)

    var frame1 = vc1.view.frame
    frame1.origin.x = self.view.frame.size.width
    vc1.view.frame = frame1

    self.addChildViewController(vc1)
    self.scrollView.addSubview(vc1.view)
    vc1.didMove(toParentViewController: self)

    let vc2 = ViewController2(nibName: "ViewController2", bundle: nil)

    var frame2 = vc2.view.frame
    frame2.origin.x = self.view.frame.size.width * 2
    vc2.view.frame = frame2

    self.addChildViewController(vc2)
    self.scrollView.addSubview(vc2.view)
    vc2.didMove(toParentViewController: self)

    let vc3 = ViewController3(nibName: "ViewController3", bundle: nil)

    var frame3 = vc3.view.frame
    frame3.origin.x = self.view.frame.size.width * 3
    vc1.view.frame = frame3

    self.addChildViewController(vc3)
    self.scrollView.addSubview(vc3.view)
    vc3.didMove(toParentViewController: self)

    self.scrollView.contentSize = CGSize(width: Double(self.view.frame.size.width * 4), height: Double(self.view.frame.size.height - 66))

}



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

回答1:

Actually I'd suggest you drop the use of UIScrollView altogether and use UIPageViewController instead. It makes this sort of thing trivial because you only have to supply one page at a time, and doing infinite or looping scrolling of the kind you describe is easy because you just keep supplying the "next" view controller in the looping series each time you are asked for it. Plus it handles the whole parent-child dance for you (not that there's anything wrong with how you're doing it).