Search code examples
cosmicmind

How do create the side-drawer controller?


I am fairly new to iOS. I have been able to successfully implement the the material buttons and card view but how the side-drawer controller is done on storyboard isn't making sense to me. Can you anyone help with sample code on storyboard?

Looking for a simple View Controller with a navigation button that opens the sidedrawercontroller.


Solution

  • In my experience, if you want to use NavigationDrawerController, you have to initialize the NavigationDrawerController programmatically.

    However, you still can layout your root view controller and side controller by storyboard, and make sure you give them proper Storyboard ID in the Interface Builder.

    Here is my code in AppDelegate.swift

    let mainViewController         = instantiateViewControllerWithIdentifier("MainViewController") as! MainViewController        
    let sideMenuViewController     = instantiateViewControllerWithIdentifier("SideMenuViewController") as! SideMenuViewController
    let navigationController       = NavigationController(rootViewController: mainViewController, leftViewController: sideMenuViewController)        
    let navigationDrawerController = NavigationDrawerController(rootViewController: navigationController)
    
    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window?.rootViewController = navigationDrawerController
    window?.makeKeyAndVisible()
    

    P.S. If you want to use UINavigationController, just embed the "MainViewController" with UINavigationViewController in storyboard, and give the UINavigationViewController a Storyboard ID. At last, set the rootViewController to your UINavigationController instance, instead of the MainViewController.

    Updated with Swift3 and Material 2.0

    func instantiateViewControllerWithIdentifier(identifier: String) -> UIViewController {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        return storyboard.instantiateViewController(withIdentifier: identifier)
    }
    
    let mainViewController = instantiateViewControllerWithIdentifier(identifier: "MainViewController") as! MainViewController
    let sideMenuViewController = instantiateViewControllerWithIdentifier(identifier: "SideMenuViewController") as! SideMenuViewController
    let navigationController = NavigationController(rootViewController: mainViewController)
    let navigationDrawerViewController = NavigationDrawerController(rootViewController: navigationController, leftViewController: sideMenuViewController, rightViewController: nil)
    
    window = UIWindow(frame: UIScreen.main.bounds)
    window?.rootViewController = navigationDrawerViewController
    window?.makeKeyAndVisible()