简体   繁体   中英

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'

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM