0

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)
Andy Kwok
  • 15
  • 5
  • 1
    you can, but when you do it that way, UIKit will look for a nib with the same name as the class (ResultViewController.xib) for instantiating, and since you are using a storyboard, I don't believe it will automatically instantiate it using the storyboard. – cohen72 Oct 08 '17 at 07:44
  • 1
    Indeed, like @YoCoh said you can do that if you have a nib file that is named the same as the view controller in your main bundle and you don't override your `init(nibName:bundle:)` with a different name and bundle. – Au Ris Oct 08 '17 at 18:39

3 Answers3

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.

  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.

  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.

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

If you still unclear, then ask.

dahiya_boy
  • 9,298
  • 1
  • 30
  • 51
0

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.

Ali Beadle
  • 4,486
  • 3
  • 30
  • 55
0

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

Taras Chernyshenko
  • 2,729
  • 14
  • 27