问题
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
.
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
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
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