简体   繁体   中英

Loading TestViewController from xib file (Everything works, but I have a question)

I had a TestViewController.swift and a TestViewController.xib presenting the layout of TestViewController.

To load this view controller I had this method :

let vc = TestViewController(nibName: "TestViewController", bundle: nil)
self.navigationController?.pushViewController(vc, animated: true)

Everything works well, but if I call empty initializer:

let vc = TestViewController()
self.navigationController?.pushViewController(vc, animated: true)

Or with nil nibname

let vc = TestViewController(nibName: nil, bundle: nil)
self.navigationController?.pushViewController(vc, animated: true)

The application also continues to work without changes. What's the point in explicitly specifying the name of the xib file? What is the difference between three calls in this case?

well,

in this part you will use if you are creating your view only using code, because you never told Xcode to load the nib file, so the nib file never loaded, so the the item that you create in the nib file is never load.

let vc = TestViewController()
self.navigationController?.pushViewController(vc, animated: true)

in this part you are telling the vc need to load first from the nib file, you have to use the name of your nib file that contain your view controller.

let vc = TestViewController(nibName: nil, bundle: nil)
self.navigationController?.pushViewController(vc, animated: true)

so, if your are using nib file you will use the second, but if you only using code for create your view controller use the first, but I usually use Storyboard instead of use nib file for create view controller.

let storyboard = UIStoryboard(name: "storybardName", bundle: nil)
let customViewController = storyboard.instantiateViewController(withIdentifier: "CustomViewController")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM