Why instantiateViewContoller is necessary?

一笑奈何 提交于 2019-12-25 08:48:38

问题


Why can't I create the view controller objects using sth like resultVC = ResultViewController() instead of the following way.

        let storyboard = UIStoryboard (name: "Main", bundle: nil)
        let resultVC = storyboard.instantiateViewController(withIdentifier: "ResultViewController") as! ResultViewController

        // Communicate the match
        resultVC.match = self.match
        self.navigationController?.pushViewController(resultVC, animated: true)

回答1:


Everything is depends on your logic. There are three basic ways by which you can create UIViewController.

  1. Storyboard : you have storyboard, design your VC and instantiate it via storyboard. In this case, you have to tell system in which storyboard your VC have and what is its ID. As you done in above code.

    • Referal : https://developer.apple.com/library/content/documentation/General/Conceptual/Devpedia-CocoaApp/Storyboard.html
  2. Xib/Nib: Like storyboard, you can use xib/nib and design your VC. Here just you need to alloc the VC by the xib name.

    • Referal : https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/LoadingResources/CocoaNibs/CocoaNibs.html
  3. Programatically: Here you donot need any type of xib/ storyboard. You have to do everything by code. your VC design will be in your respective VC file. Here you have to just alloc that file.

    • Referal : How to make a view controller without a xib or a storyboard vc identifier? or starting ios project without storyboard

Difference: Which is more efficient way? StoryBoard or XIB?

If you still unclear, then ask.




回答2:


You use this method to create view controller objects that you want to manipulate and present programmatically in your application. Before you can use this method to retrieve a view controller, you must explicitly tag it with an appropriate identifier string in Interface Builder.

So, you doesn't just allocate your class, but associate your class with appropriative screen in your Interface Builder.

Anyway, you can create your controller like you want resultVC = ResultViewController() but you should create all UI in code instead of using Interface Builder




回答3:


Using resultVC = ResultViewController() will create a view controller of type ResultViewController but without any links to your storyboard, which is unlikely to be of any use to you (why are you using a storyboard if not to gain these links?). You need to instantiate it from the storyboard to gain these links.



来源:https://stackoverflow.com/questions/46628492/why-instantiateviewcontoller-is-necessary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!