Custom init for UIViewController in Swift with interface setup in storyboard

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

    One way that I've done this is with a convenience initializer.

    class MemeDetailVC : UIViewController {
    
        convenience init(meme: Meme) {
            self.init()
            self.meme = meme
        }
    }
    

    Then you initialize your MemeDetailVC with let memeDetailVC = MemeDetailVC(theMeme)

    Apple's documentation on initializers is pretty good, but my personal favorite is the Ray Wenderlich: Initialization in Depth tutorial series which should give you plenty of explanation/examples on your various init options and the "proper" way to do things.


    EDIT: While you can use a convenience initializer on custom view controllers, everyone is correct in stating that you cannot use custom initializers when initializing from the storyboard or through a storyboard segue.

    If your interface is set up in the storyboard and you're creating the controller completely programmatically, then a convenience initializer is probably the easiest way to do what you're trying to do since you don't have to deal with the required init with the NSCoder (which I still don't really understand).

    If you're getting your view controller via the storyboard though, then you will need to follow @Caleb Kleveter's answer and cast the view controller into your desired subclass then set the property manually.

提交回复
热议问题