iOS: How do I swipe between views using Swift
Asked Answered
S

2

9

I'm new to Swift and iOS development, and am looking how to set up a main view where I want swipe right for a second view or left for a third view. When I am in the second or the third view it should be possible to swipe back to the main view.

I found several ideas how to realize swipe view like this one: https://medium.com/swift-programming/ios-swipe-view-with-swift-44fa83a2e078

But the "problem" is, that I want to start on a main view with the possibility to swipe in both directions. (so with the solution above to start on the second view)

Does anyone know how to do this?

Sepal answered 25/9, 2014 at 8:18 Comment(1)
Possible duplicate of UIPageViewController and storyboardMisprision
M
7

It's this easy ...

https://mcmap.net/q/145170/-uipageviewcontroller-and-storyboard

enter image description here

Misprision answered 25/9, 2014 at 8:43 Comment(0)
S
3

This code works together with Swift & Storyboarding (in the View Controller):

import UIKit

class ViewController : UIViewController, UIPageViewControllerDataSource {
    var myViewControllers = Array(count: 3, repeatedValue:UIViewController())

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        let pvc = segue.destinationViewController as UIPageViewController

        pvc.dataSource = self

       let storyboard = UIStoryboard(name: "Main", bundle: nil);

        var vc0 = storyboard.instantiateViewControllerWithIdentifier("shopID") as UIViewController
        var vc1 = storyboard.instantiateViewControllerWithIdentifier("startID") as UIViewController
        var vc2 = storyboard.instantiateViewControllerWithIdentifier("avatarID") as UIViewController

        self.myViewControllers = [vc0, vc1, vc2]

        pvc.setViewControllers([myViewControllers[1]], direction:.Forward, animated:false, completion:nil)

        println("Loaded")
    }

    func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
        var currentIndex =  find(self.myViewControllers, viewController)!+1
        if currentIndex >= self.myViewControllers.count {
            return nil
        }
        return self.myViewControllers[currentIndex]
    }

    func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
        var currentIndex =  find(self.myViewControllers, viewController)!-1
        if currentIndex < 0 {
            return nil
        }
        return self.myViewControllers[currentIndex]
    }

}
Sepal answered 30/9, 2014 at 12:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.