子类化 UIView

Subclassing a UIView

我正在尝试使用自定义初始化程序子class UIView,但 运行 出现多个错误。

class ProgressAlertView: UIView {

    var title: String

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

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

    convenience init(title: String) {
        self.title = title
        self.init(title: title)
    }
}

上面的代码将导致多条错误消息,其中包括我在便利初始化中的变量标题:'self' used in 属性 access 'title' before 'self.init'打电话

Swift 但是要求 super class 中的所有初始化程序必须在一个初始化其他实例变量之后调用。所以错误一定在别的地方。

非常感谢这里的提示。

想想你期望在……

中发生什么
override init(frame: CGRect) {
    super.init(frame: frame)
    alertLayout()
}

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

您有一个非可选的实例变量 title。这两种情况应该如何取值?

而在你的第 3 个 init

convenience init(title: String) {
    self.title = title
    self.init(title: title)
}

init(title: String) 调用 init(title: String),后者又调用 init(title: String),等等。您处于无限递归区域。

如果你想在代码中实例化视图,你需要类似...

init(title: String, frame: CGRect) {
    self.title = title
    super.init(frame: frame)
    alertLayout()
}

您还需要实施

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

如果您在情节提要/笔尖中使用它,那么您需要……

required init?(coder aDecoder: NSCoder) {
    self.title = ""
    super.init(coder: aDecoder)
}

之后再给title赋值