Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 760
Sunny Shah Avatar asked Nov 24 '14 06:11

Sunny Shah


People also ask

How do I load a view in Swift?

In the XIB, I changed the "File's Owner" class to SomeView (in the identity inspector). I created a UIView outlet in SomeView. swift, linking it to the top level view in the XIB file (named it "view" for convenience). I then added other outlets to other controls in the XIB file as needed.


Video Answer


3 Answers

var viewController = OfferDetailViewController(nibName: "OfferDetailViewController", bundle: nil)
like image 127
aelam Avatar answered Oct 11 '22 18:10

aelam


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()
like image 22
Ankit Srivastava Avatar answered Oct 11 '22 18:10

Ankit Srivastava


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"
like image 11
dr OX Avatar answered Oct 11 '22 17:10

dr OX