Custom init for UIViewController in Swift with interface setup in storyboard

后端 未结 12 2104
长情又很酷
长情又很酷 2020-11-27 05:08

I\'m having issue for writing custom init for subclass of UIViewController, basically I want to pass the dependency through the init method for viewController rather than se

12条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 05:37

    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())
    

提交回复
热议问题