Search code examples
swiftuiviewcontrollerinitialization

How do I make a custom initializer for a UIViewController subclass in Swift?


Apologies if this has been asked before, I've searched around a lot and many answers are from earlier Swift betas when things were different. I can't seem to find a definitive answer.

I want to subclass UIViewController and have a custom initializer to allow me to set it up in code easily. I'm having trouble doing this in Swift.

I want an init() function that I can use to pass a specific NSURL I'll then use with the view controller. In my mind it looks something like init(withImageURL: NSURL). If I add that function it then asks me to add the init(coder: NSCoder) function.

I believe this is because it's marked in the superclass with the required keyword? So I have to do it in the subclass? I add it:

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

Now what? Is my special initializer considered a convenience one? A designated one? Do I call a super initializer? An initializer from the same class?

How do I add my special initializer onto a UIViewController subclass?


Solution

  • class ViewController: UIViewController {
            
        var imageURL: NSURL?
        
        // this is a convenient way to create this view controller without a imageURL
        convenience init() {
            self.init(imageURL: nil)
        }
        
        init(imageURL: NSURL?) {
            self.imageURL = imageURL
            super.init(nibName: nil, bundle: nil)
        }
        
        // if this view controller is loaded from a storyboard, imageURL will be nil
        
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
    }