首页 > 解决方案 > 使用 init 子类化 UIView

问题描述

我已经尝试了以前问题的所有答案,但是当我尝试继承 UIView 并添加我自己的初始化程序时仍然遇到错误。这是代码:

class ProgressAlertView: UIView {
    var title: String
    var steps: Int
    var messageLabels: [String]
    var errorLabel: String
    var successLabel: String

    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        alertLayout()
    }

    public override init(frame: CGRect) {
        super.init(frame: frame)
        alertLayout()
    }

    convenience init(title: String, steps: Int, messageLabels: [String], errorLabel: String, successLabel: String) {
        self.init(frame: frame)
        self.title = title
        self.steps = steps
        self.messageLabels = messageLabels
        self.errorLabel = errorLabel
        self.successLabel = successLabel
    }
}

这会在 required 和 override 方法中引发此错误:

属性“self.title”未在 super.init 调用中初始化

在对上一个问题的回答中,有人解释说需要在调用 super.init() 之前先设置参数。当我尝试这样做时,我收到以下错误消息(在上面的错误消息之上):'self' used in property access 'title' before 'self.init' call

这样做的正确方法是什么?

标签: swiftclassuiviewinit

解决方案


推荐阅读