Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot subclass UIButton: Must call a designated initializer of the superclass 'UIButton'

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()
        ...
    }
}
like image 316
Crashalot Avatar asked Sep 02 '15 01:09

Crashalot


1 Answers

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.

like image 97
Aaron Brager Avatar answered Oct 17 '22 21:10

Aaron Brager