I have my Swift class as the simple code below:
class FavoriteView: UIView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
convenience init() {
self.init(frame: CGRectZero)
}
private func commonInit() {
// init something
}
// MY PROBLEM IS HERE
var favoriteCount: Int = 0 {
didSet {
// update the view
}
}
}
The logic is whenever the favoriteCount
is set to a new value, the code in didSet
is run.
It runs well. But the problem is that code (in didSet
) is not run for the very first time. I mean when a new FavoriteView
instance is initialized, I assume it to run also, but it's not.
Is there any way to run that code (in didSet
) for the first time.
Thank you!
didSet
observer not invoked with default values, as well as it not invoked when you setting up properties in init
methods (due to self
not initialized yet). You may write separated method updateView
and invoke it in init
method and in didSet
observer.
private func commonInit() {
updateView()
// init something
}
// MY PROBLEM IS HERE
var favoriteCount: Int = 0 {
didSet {
updateView()
}
}
func updateView() {
//code that you wanted to place in observer
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With