I sometimes see a view made like this where there is the same setup() function in two different init methods. What is the difference between the init methods and why is the same setup() being called in both..?
class BigButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } fileprivate func setup() { // set up stuff } }
Override initializer In Swift initializers are not inherited for subclasses by default. If you want to provide the same initializer for a subclass that the parent class already has, you have to use the override keyword.
Required initializers will be explained in this article. If we write a required modifier before the definition of init method in a class that indicates that every subclass of that class must implement that initializer. There are various things related to required initializer.
There is no functional difference between the two. Both styles will call the same initializer and produce the same value.
Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.
override init(frame: CGRect)
is used when you create the view (in this case the button) programmatically.
required init?(coder: NSCoder)
is used when the view is created from storyboard/xib.
since the latter is required you must implement its body. However if you are not going to create the button manually the first one is not required and can be omitted
setup is called in both because however you choose to create the button you want to setup its custom behavior so it will work as you intended it to
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