Sunny Shah
Sunny Shah

Reputation: 13020

Load UIViewController from the separate nib file in swift?

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?

Upvotes: 25

Views: 37069

Answers (3)

dr OX
dr OX

Reputation: 4759

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"

Upvotes: 12

Ankit Srivastava
Ankit Srivastava

Reputation: 12405

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()

Upvotes: 22

aelam
aelam

Reputation: 2916

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

Upvotes: 52

Related Questions