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

删除回忆录丶 提交于 2020-01-24 02:21:06

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/32343198/cannot-subclass-uibutton-must-call-a-designated-initializer-of-the-superclass

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!