Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement variable attribute property observer in Swift

I want to implement a didSet over a "sub-attribute" of a variable.

Example:

@IBOutlet weak var myLabel: UILabel!
var myLabel.hidden { didSet{ "DO SOMETHING" } }

I want to hide/show some other views when myLabel.hidden attribute change. How can I do it?

like image 366
Daniel Gomez Rico Avatar asked Feb 11 '23 18:02

Daniel Gomez Rico


2 Answers

You can make a property like this

    var hideLabel: Bool = false {
    didSet {
        myLabel.isHidden = hideLabel
        //SHOW OR HIDE OTHER VIEWS
    }
}

By doing this you don't have to use KVO at the same time you can add more controls to hide to show at didSet context. I Believe this is a simpler way to do such a thing.

like image 88
Amjad Husseini Avatar answered Feb 13 '23 06:02

Amjad Husseini


The standard process is to use KVO. Add observer when the view is loaded:

override func viewDidLoad() {
    super.viewDidLoad()

    label.addObserver(self, forKeyPath: "hidden", options: .New | .Old, context: nil)
}

When the view controller is deallocated, make sure to remove the observer.

deinit {
    label.removeObserver(self, forKeyPath: "hidden")
}

And do whatever you want inside the observeValueForKeyPath method:

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
    NSLog("\(change)")

    // do whatever you want here
}
like image 36
Rob Avatar answered Feb 13 '23 07:02

Rob