Swift-设置后willSet和didSet不被调用
2021-07-21 本文已影响0人
大也
在初始化(init)的方法内写是无效的
哪怕是data数组字段设置都一样
所以init初始化传数组 set后
willSet&didSet不调用 我遇到的就是这样的情况
在初始化(init)的方法内写是无效的,但是又需要在初始化的时候调用didSet,那么可以采用KVC的方式给对象初始化,就可以调用willSet&didSet了
override init(frame: CGRect) {
super.init(frame: frame)
setValue(true, forKey: "isConnect")
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
guard let newValue = value as? Bool else {
return
}
isConnect = newValue
}
var isConnect : Bool = false {
didSet {
}
}