Custom init for UIViewController in Swift with interface setup in storyboard

后端 未结 12 2109
长情又很酷
长情又很酷 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:38

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

提交回复
热议问题