Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It shows "required initializer init must be provided in subclass of UIControl" When I override init(frame: CGRect)

This code works:

import UIKit

class wheel: UIControl {

}

But this code doesn't:

class wheel: UIControl {
override init(frame: CGRect) {
    super.init(frame: frame)
}

It shows error "required initializer init must be provided in subclass of UIControl" when I override init(frame: CGRect) but not init(coder aDecoder: NSCoder).

Why do I have to implement init(coder aDecoder: NSCoder)? And why don't I need to implement it if I didn't implement init(frame: CGRect)?

I found a similar Stack Overflow post but it didn't explain: Swift : Error: 'required' initializer 'init(coder:)' must be provided by subclass of 'UIView'

like image 492
allenlinli Avatar asked Apr 08 '16 14:04

allenlinli


2 Answers

Look. According to Apple documentations Swift subclasses do not inherit their superclass initializers by default. They are inherited only in certain circumstances, one of which is: If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers. So if you're not implementing init(frame: CGRect) all super initializers are inherited.

Also UIView adopts NSCoding protocol, which requires an init(coder:) initializer. So if you're implementing init(frame: CGRect), your class is no longer inheriting super initializers. So you must implement that one too:

required init?(coder decoder: NSCoder) {
    super.init?(coder: decoder)
}
like image 196
iyuna Avatar answered Nov 05 '22 16:11

iyuna


When creating your model Object subclasses, you may sometimes want to add your own custom initialization methods for added convenience.

Due to some present limitations with Swift introspection, these methods cannot be designated initializers for the class. Instead, they need to be marked as convenience initializers using the Swift keyword of the same name like this

like image 40
Nikita Teslyuk Avatar answered Nov 05 '22 17:11

Nikita Teslyuk