Trying to subclass UIButton but the error Must call a designated initializer of the superclass 'UIButton'
occurs.
Researching several SO posts like this, this, this, or several others did not help as those solutions didn't work.
How can we subclass UIButton
in Swift and define a custom init function?
import UIKit
class KeyboardButton : UIButton {
var letter = ""
var viewController:CustomViewController?
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(letter: String, viewController: CustomViewController) {
super.init()
...
}
}
You have to call the superclass' designated initializer:
Swift 3 & 4:
init(letter: String, viewController: CustomViewController) {
super.init(frame: .zero)
}
Swift 1 & 2:
init(letter: String, viewController: CustomViewController) {
super.init(frame: CGRectZero)
}
As Paulw11 says in the comments, a view generally shouldn't have a reference to its controller, except as a weak reference using the delegate pattern, which would promote reusability.
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