Custom init for UIViewController in Swift with interface setup in storyboard Custom init for UIViewController in Swift with interface setup in storyboard ios ios

Custom init for UIViewController in Swift with interface setup in storyboard


As it was specified in one of the answers above you can not use both and custom init method and storyboard.

But you still can use a static method to instantiate ViewController from a storyboard and perform additional setup on it.

It will look like this:

class MemeDetailVC : UIViewController {        var meme : Meme!        static func makeMemeDetailVC(meme: Meme) -> MemeDetailVC {        let newViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "IdentifierOfYouViewController") as! MemeDetailVC                newViewController.meme = meme                return newViewController    }}

Don't forget to specify IdentifierOfYouViewController as view controller identifier in your storyboard. You may also need to change the name of the storyboard in the code above.


You can't use a custom initializer when you initialize from a Storyboard, using init?(coder aDecoder: NSCoder) is how Apple designed the storyboard to initialize a controller. However, there are ways to send data to a UIViewController.

Your view controller's name has detail in it, so I suppose that you get there from a different controller. In this case you can use the prepareForSegue method to send data to the detail (This is Swift 3):

override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {    if segue.identifier == "identifier" {        if let controller = segue.destinationViewController as? MemeDetailVC {            controller.meme = "Meme"        }    }}

I just used a property of type String instead of Meme for testing purposes. Also, make sure that you pass in the correct segue identifier ("identifier" was just a placeholder).


As @Caleb Kleveter has pointed out, we can't use a custom initializer while initialising from a Storyboard.

But, we can solve the problem by using factory/class method which instantiate view controller object from Storyboard and return view controller object.I think this is a pretty cool way.

Note: This is not an exact answer to question rather a workaround to solve the problem.

Make class method, in MemeDetailVC class, as follows:

// Considering your view controller resides in Main.storyboard and it's identifier is set to "MemeDetailVC"class func `init`(meme: Meme) -> MemeDetailVC? {    let storyboard = UIStoryboard(name: "Main", bundle: nil)    let vc = storyboard.instantiateViewController(withIdentifier: "MemeDetailVC") as? MemeDetailVC    vc?.meme = meme    return vc}

Usage:

let memeDetailVC = MemeDetailVC.init(meme: Meme())