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?
Unlike Objective-C initializers, Swift initializers don't return a value. Their primary role is to ensure that new instances of a type are correctly initialized before they're used for the first time.
Swift defines two kinds of initializers for class types to help ensure all stored properties receive an initial value. Designated initializers are the primary initializers for a class.
The NSCoding protocol requires that you implement the required initializer init?(coder aDecoder: NSCoder). This initializer is what allows you to unarchive the ViewController using aDecoder object.
An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }
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) } }
For those who write UI in code
class Your_ViewController : UIViewController { let your_property : String init(your_property: String) { self.your_property = your_property super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() } required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With