Load UIViewController from the separate nib file in swift?

34,574

Solution 1

var viewController = OfferDetailViewController(nibName: "OfferDetailViewController", bundle: nil)

Solution 2

Here is a nice generic approach...

extension UIViewController {
    class func loadFromNib<T: UIViewController>() -> T {
         return T(nibName: String(describing: self), bundle: nil)
    }
}

let vc : OfferDetailViewController = OfferDetailViewController.loadFromNib()

Solution 3

solution with type casting:

extension UIViewController {
    static func initFromNib() -> Self {
        func instanceFromNib<T: UIViewController>() -> T {
            return T(nibName: String(describing: self), bundle: nil)
        }
        return instanceFromNib()
    }
}

enjoyment:

let testVC = TestVC.initFromNib()
testVC.someCustomParam = "someValue"
Share:
34,574
Sunny Shah
Author by

Sunny Shah

I am intensely passionate about, and skilled in, engineering Mac OS X, iOS and Tizen applications. I have efficiency to execute the ideas in an efficient way. Now it has been above 4+ years experience. Experience developing and designing an enterprise application. Comprehensive knowledge of software development (Computer programming, documenting , Testing, deployment,Bug fixing, etc.) Skype ID: Sunny.shah.d Email: [email protected]

Updated on October 19, 2020

Comments

  • Sunny Shah
    Sunny Shah over 3 years

    I had take one ViewController with separate nib file. and my initial root viewcontroller is set in the storyBoard. Now the problem is that when I push to this controller the View hireachy methods are not being called (ViewDidLoad , ViewWillApper , etc)..

    Code (View is loaded but methods are not calling)

    var viewController = UIViewController(nibName: "OfferDetailViewController", bundle: nil) as OfferDetailViewController
     self.navigationController?.pushViewController(viewController, animated: true);
    

    The same thing if i do with the storyboard its working fine.

        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        var viewController = mainStoryboard.instantiateViewControllerWithIdentifier("offer") as OfferDetailViewController     
       self.navigationController?.pushViewController(viewController, animated: true);
    

    Problem : With storyboard View hierarchy methods are calling but not with the separate nib file?