0

I always initialise my view controllers from the storyboard like this:

let controller = storyboard!.instantiateViewController(withIdentifier: "MyViewController") as! MyViewController

I want to initialise variables on init. Usually I just assign them to the controller like controller.variable = x. I'd prefer to use the init() function, but it seems I can't if I use the storyboard. What's the best way to do this?

Tometoyou
  • 7,792
  • 12
  • 62
  • 108
  • 2
    Possible duplicate of [Custom init of UIViewController from storyboard](https://stackoverflow.com/questions/30449137/custom-init-of-uiviewcontroller-from-storyboard) – Nilanshu Jaiswal Nov 29 '18 at 13:12
  • Create your own method(ex: setup) and add your init codes there and call it when your view controller initialized. Ex: `controller.setup()` – Natarajan Nov 29 '18 at 13:15

1 Answers1

1

I don't think so it will be useful if you create own init() for ViewController.

You can simply use like below:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
    controller.pageTitle = "XYZ"
    controller.pageNumber = 2

If you want to pass multiple values to the destination controller, then you can pass the model class as well if all the values define a category class.

nitin.agam
  • 1,949
  • 1
  • 17
  • 24