Aidan Sawyer
Aidan Sawyer

Reputation: 45

How do make a UIScrollview only show one subview at a time

I followed a tutorial: https://www.youtube.com/watch?v=1_daE3IL_1s that teaches you how to make a snap-chat like menu in swift 3, where every time you swipe a new subview is put on the screen, but it is the only one and you need to swipe another time to get the next view. This tutorial was made in swift 2, but when I updated to swift 3 the scrollview is now acting like normal scroll view where it scrolls fluently. is there any way to fix this?

code for main view controller:

class ViewController: UIViewController {

    @IBOutlet weak var scrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let V1: View1 = View1(nibName: "View1", bundle: nil)
        let V2: View2 = View2(nibName: "View2", bundle: nil)
        let V3: View3 = View3(nibName: "View3", bundle: nil)

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

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

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

        var V2Frame: CGRect = V2.view.frame
        V2Frame.origin.x = self.view.frame.width
        V2.view.frame = V2Frame

        var V3Frame: CGRect = V3.view.frame
        V3Frame.origin.x = 2 * self.view.frame.width
        V3.view.frame = V3Frame

        self.scrollView.contentSize = CGSize(width: self.view.frame.width*3 , height: self.view.frame.size.height)
    }

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

}

Upvotes: 1

Views: 289

Answers (1)

shallowThought
shallowThought

Reputation: 19602

Enable paging:

override func viewDidLoad() {
    super.viewDidLoad()
    scrollView.isPagingEnabled = true
    // ...
}

Upvotes: 3

Related Questions