简体   繁体   中英

Load another ViewController that exists in Storyboard after event in Swift

When I rotate my Device I would want to load a completely different MasterView which I have in Storyboard.

In AppDelegate I have

func rotated() {

    if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)) {
        // Here I would like to load LandscapeViewController
    }

    if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)) {
        // or load PortraitViewController
    }

}

Any Advice how to achieve this?

I know there is .loadView() but I don't think this is the right way or I was doing something wrong...

You need to use the method called viewWillTransitionToSize since didRotateFromInterfaceOrientation was deprecated in iOS 8.

The final code would look something like this:

 override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {

         if size.width > size.height {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            var secondViewController = storyboard.instantiateViewControllerWithIdentifier("landscape") as? UIViewController

            if let newVC = secondViewController{
                //If you have a container add newVC as a childViewController, else present the view
                println("landscape")
            }


        }

         else if size.width < size.height{
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            var secondViewController = storyboard.instantiateViewControllerWithIdentifier("portrait") as? UIViewController

            if let newVC = secondViewController{
                //If you have a container add newVC as a childViewController, else present the view
                println("portrait")
            }
        }


}

You can instantiate the view controller from the storyboard.

If you embed PortraitViewController in a UINavigationController you could then push the LandscapeViewController on rotation?

var storyboard = UIStoryboard(name: "Main", bundle: nil)
var viewController: LandscapeViewControllerViewController = storyboard.instantiateViewControllerWithIdentifier("LandscapeViewControllerViewController") as LandscapeViewController

var rootViewController = self.window!.rootViewController as UINavigationController

if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)) {
   rootViewController.pushViewController(viewController, animated: true)
}

if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)) {
   rootViewController.popViewController()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM