0

Lets say I have 2 classes.

1) class ViewControllerA: UIViewController
2) class ViewControllerB: UIViewController

In addition, I have 2 scenes in my Main.storyboard file

1) scene that has a green background attached to ViewControllerA with 1 button
2) scene that has a blue background attached to ViewControllerB

Is there a difference between me instantiating B

let newScene = ViewControllerB()
self.present(newScene, animated: true, completion: nil)

as opposed to using a storyboard helper method

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newScene = storyBoard.instantiateViewController(withIdentifier: "ViewControllerB") as! ViewControllerB
self.present(newScene, animated: true, completion: nil)

If there is a difference, why are they different?

iGatiTech
  • 2,306
  • 1
  • 21
  • 45
AlanSTACK
  • 5,525
  • 3
  • 40
  • 99

1 Answers1

1

Is there a difference between me instantiating B as opposed to using a storyboard helper method.

Absolutely

Storyboards do a lot of awesome stuff for us (if setup correctly). However, if you instantiate a view controller yourself, you have to setup everything yourself. That means, you have to instantiate the view, connect control events to methods, configure the look and feel of the UI, etc...all in code. Storyboards turn all of that code into a resource file and do most of the work for us.

For example:

In storyboard, you can connect an event in a control to an method in your view controller that's marked with @IBAction. But if you don't use storyboards then you have to wire up the control events yourself:

self.myButton.addTarget(self, action: #selector(buttonTapped:), for: .touchUpInside)
Jake
  • 13,097
  • 9
  • 44
  • 73
  • Thanks for your answer. Could you include a link to how to link views, actions, etc to view controllers? I am having some trouble finding anything... – AlanSTACK Feb 20 '18 at 05:52
  • Here's how to add buttons. Adding views are pretty much the same, but you don't have to add a target: https://stackoverflow.com/questions/24030348/how-to-create-a-button-programmatically – Jake Feb 20 '18 at 05:56
  • One last thing, can we think of an entire storyboard `Scene` just as a `ViewContrroller` with certain attributes set, then? – AlanSTACK Feb 20 '18 at 05:57
  • Pretty much...but it set attributes for both the view controller and the view controller's view and its subviews as well. – Jake Feb 20 '18 at 05:58