Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple storyboards in Swift

Tags:

ios

swift

iphone

I have an app which has 4 storyboards, each for a different device (iphone4, 5, 6, 6+). I have tried to use auto constraints but since my app is complicated, I wasn't able to figure it out. I have heard that if you have multiple storyboards there should be a way of specifying which storyboard to use in the app delegate. How do I go about specifying the proper storyboard for the proper device in the app delegate? I currently have four storyboards, named:

iphone4s.storyboard
iphone5.storyboard
iphone6.storyboard
iphone6plus.storyboard

Thank you.

like image 439
Josh O'Connor Avatar asked Jul 02 '15 04:07

Josh O'Connor


3 Answers

According to me these days we make use of autoLayout which knows how to layout its view for depending on screen size and constraints

As you asked you can override the storyboard from AppDelegate in applicationdidFinishLaunchingWithOptions method

    let storyBoard : UIStoryboard = UIStoryboard(name: "iphone4s", bundle: nil)
    //you can check your device and override the storyboard name
    let initialViewController: UIViewController =  storyBoard.instantiateInitialViewController()!
    self.window?.rootViewController? = initialViewController
like image 173
Shailesh Chandavar Avatar answered Nov 12 '22 17:11

Shailesh Chandavar


Implement a function that retrieves the storyboard when it's name is specified.

func getStoryBoard(name : String)-> UIStoryboard
{
    var storyBoard = UIStoryboard(name: name, bundle: nil);
    return storyBoard;
}

Change the app delegate method like:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
    var storyBoard = getStoryBoard("Main") // Change the storyboard name based on the device, you may need to write a condition here for that
    var initialViewController: UIViewController = storyBoard.instantiateInitialViewController() as! UIViewController
    self.window?.rootViewController = initialViewController
    self.window?.makeKeyAndVisible()
    // Override point for customization after application launch.
    return true
}
like image 1
Midhun MP Avatar answered Nov 12 '22 17:11

Midhun MP


In order to launch different storyboards for various device, you need to override rootViewController Object.

       var myDeviceStoryboard : UIStoryboard = UIStoryboard(name: "DeviceStoryboard", bundle: NSBundle.mainBundle())
var firstVC : MyDeviceFirstViewController = myDeviceStoryboard.instantiateViewControllerWithIdentifier("MyDeviceFirstViewController") as! MyDeviceFirstViewController
self.window?.rootViewController = MyDeviceFirstViewController //This should be a navigation controller

Also, you need to override few settings in Project settings, and Storyboard. Refer images attached.enter image description here

like image 1
Meet Avatar answered Nov 12 '22 18:11

Meet