gpt4 book ai didi

ios - 在 Init 函数外初始化类属性

转载 作者:行者123 更新时间:2023-11-28 13:01:05 26 4
gpt4 key购买 nike

抱歉,如果这是一个基本问题,但我无法在任何地方找到解决方案。我想在 Init 之外的函数中初始化类属性,并且只从构造函数内部调用它。我这样做是为了避免代码重复,因为当前版本如下所示:

public class WifiNameDisplay: UIView {
var wifiImageView: UIImageView
var networkName: UILabel
public var networkSSID: String {
didSet {
networkName.text = networkSSID
adjustSizeToContent()
}
}

override public init(frame: CGRect) {
networkSSID = "NETWORK"
wifiImageView = UIImageView(image: UIImage(named: "wifi_icon.png")!)
networkName = UILabel(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 400, height: wifiImageView.frame.size.height)))

super.init(frame: frame)
}


convenience public init() {
self.init(frame: CGRect.zero)
}

required public init(coder aDecoder: NSCoder) {
networkSSID = "NETWORK"
wifiImageView = UIImageView(image: UIImage(named: "wifi_icon.png")!)
networkName = UILabel(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 400, height: wifiImageView.frame.size.height)))

super.init(coder: aDecoder)!
}
}

我想把它改成这样:

public class WifiNameDisplay: UIView {
var wifiImageView: UIImageView
var networkName: UILabel
public var networkSSID: String {
didSet {
networkName.text = networkSSID
adjustSizeToContent()
}
}

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


convenience public init() {
self.init(frame: CGRect.zero)
}

required public init(coder aDecoder: NSCoder) {
initDefaultValues()
super.init(coder: aDecoder)!
}

func initDefaultValues() {
networkSSID = "NETWORK"
wifiImageView = UIImageView(image: UIImage(named: "wifi_icon.png")!)
networkName = UILabel(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 400, height: wifiImageView.frame.size.height)))
}
}

问题是编译器不允许这样做,调用“在 super.init 初始化 self 之前在方法调用‘initDefaultValues’中使用‘self’”。我想要的是可能的,还是我被迫使用重复代码?

最佳答案

如果您将属性声明为隐式展开的可选值,那么您可以在调用父类(super class)初始化函数后初始化它们 -

public class WifiNameDisplay: UIView {
var wifiImageView: UIImageView!
var networkName: UILabel!
public var networkSSID: String! {
didSet {
networkName.text = networkSSID
// adjustSizeToContent()
}
}

override public init(frame: CGRect) {

super.init(frame: frame)
initDefaultValues()
}


convenience public init() {
self.init(frame: CGRect.zero)
}

required public init(coder aDecoder: NSCoder) {

super.init(coder: aDecoder)!
initDefaultValues()
}

func initDefaultValues() {
networkSSID = "NETWORK"
wifiImageView = UIImageView(image: UIImage(named: "wifi_icon.png")!)
networkName = UILabel(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 400, height: wifiImageView.frame.size.height)))
}
}

关于ios - 在 Init 函数外初始化类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33802509/

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