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.

Leave a Comment