不能继承 UIButton:必须调用超类“UIButton"的指定初始值设定项 [英] Cannot subclass UIButton: Must call a designated initializer of the superclass 'UIButton'

查看:26
本文介绍了不能继承 UIButton:必须调用超类“UIButton"的指定初始值设定项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试对 UIButton 进行子类化,但发生错误 Must call a specified initializer of the superclass 'UIButton'.

Trying to subclass UIButton but the error Must call a designated initializer of the superclass 'UIButton' occurs.

研究几个 SO 帖子像这样这个这个,或者其他几个没有帮助,因为这些解决方案不起作用.

Researching several SO posts like this, this, this, or several others did not help as those solutions didn't work.

我们如何在 Swift 中继承 UIButton 并定义一个自定义的 init 函数?

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:

斯威夫特 3 &4:

init(letter: String, viewController: CustomViewController) {
    super.init(frame: .zero)
}

Swift 1 &2:

init(letter: String, viewController: CustomViewController) {
    super.init(frame: CGRectZero)
}

正如 Paulw11 在评论中所说,视图通常不应引用其控制器,除非作为使用委托模式的弱引用,这将提高可重用性.

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.

这篇关于不能继承 UIButton:必须调用超类“UIButton"的指定初始值设定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆