Arunabh Das
Arunabh Das

Reputation: 14392

How to load a UIViewController programmatically without using Storyboard in Swift

I have a ViewController called MyViewController and I want to load it programmatically without a stroyboard or xib.

As a follow up squestion, I would like to load a MyTableViewController inside a navigation controller. Again, I need to do it programmatically without using Storyboard or xib.

Please help.

Upvotes: 4

Views: 3592

Answers (1)

Arunabh Das
Arunabh Das

Reputation: 14392

I was able to solve my issue by removing the Storyboard and using the following code in AppDelegate

    import UIKit
    import CoreData

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {

        var window: UIWindow?
        var navigationController: UINavigationController?

        func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
            // Override point for customization after application launch.
            self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
            // Override point for customization after application launch.
            self.window!.backgroundColor = UIColor.whiteColor()
            self.window!.makeKeyAndVisible()

            let myViewController: MyViewViewController? = MyViewViewController()
            self.navigationController = UINavigationController(rootViewController: myViewController!)
            self.window!.rootViewController = self.navigationController
            return true
        }
 ...
}

Upvotes: 1

Related Questions