gpt4 book ai didi

ios - 强制用户使用自定义 init 方法进行初始化

转载 作者:行者123 更新时间:2023-11-28 09:52:01 24 4
gpt4 key购买 nike

我正在创建一个 UIView 子类,目的是强制用户使用我需要的 init 方法而不是默认方法。

为此,我为此创建了一个方便的方法。

@available(*, unavailable, message: "init is unavailable.")
public override init(frame: CGRect) {
super.init(frame: frame)
}

required
convenience public init(withSomeParameters myParam:Type) {
self.init(frame: CGRect.zero)
//Doing something nice!
}

这行得通!但是,当我尝试 init 时,它向我展示了两种初始化方法。如何强制用户使用自定义 init 方法?

最佳答案

您可以将其设为私有(private),因此用户必须使用 withSomeParameters 初始化测试类

class Test:UIView {
private override init(frame: CGRect) {
super.init(frame: frame)
}

convenience public init(withSomeParameters myParam:Type) {
self.init(frame: CGRect.zero)
//Doing something nice!
}

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

关于ios - 强制用户使用自定义 init 方法进行初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45144394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com