Search code examples
iosswiftinitializationoverridinginitializer

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'


Solution

  • 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)
    }