iOS 自定义初始化问题,如何设置默认初始化方法?

iOS custom init issue, how to set the default init method?

我有一个自定义 UILabel class。

class CustomLabel: UILabel{


    init(_ title: String = "Star"){
        super.init(frame: CGRect.zero)
        text = title
    }

    override init(frame: CGRect) {
        fatalError("Not Implemented")
    }


    required init?(coder aDecoder: NSCoder) {
        fatalError("Not Implemented")
    }


}

我这样叫就可以了

let head = CustomLabel("Front")

这样叫不好

let lhs = CustomLabel()

Xcode 报告:未实施,程序在此处停止。

override init(frame: CGRect) {
     fatalError("Not Implemented")
}

显然let lhs = CustomLabel()调用方法override init(frame: CGRect) {,

如何使 init(_ title: String = "Star"){ 默认?

即。让Xcode先找到。

删除您实施的其他 init 并根据需要设置您的

class CustomLabel: UILabel {

    required init(_ title: String = "Star"){
        super.init(frame: CGRect.zero)
        text = title
    }

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

}

let label1 = CustomLabel()
print(label1)

这有效并使用预期的初始化

编辑:

Bastian 在他们的回答中提供了一个有用的 link,但后来将其删除。

link:Adding Swift Convenience Initializers

来自 link 的有用片段(以防 link 中断):

Designated or Convenience?

First a recap on the two types of initializer:

A designated initializer is the primary initializer for a class. It must fully initialize all properties introduced by its class before calling a superclass initializer. A class can have more than one designated initializer.

A convenience initializer is a secondary initializer that must call a designated initializer of the same class. It is useful when you want to provide default values or other custom setup. A class does not require convenience initializers.

The Three rules

With that clear you need to remember three rules for designated and convenience initializers for class types:

  • A designated initializer must call a designated initializer from the immediate superclass.
  • A convenience initializer must call another initializer from the same class.
  • A convenience initializer must ultimately call a designated initializer.

What does this mean for us? In simple terms, do not call super from your convenience initializer. Call another initializer (convenience or designated) from the same class.