smeshko
smeshko

Reputation: 1226

Observe change in a property inside property

I was wandering if it was possible to use didSet for a property inside a property.

Let's say I have a function resize() that I want to call every time the text property of a UILabel is set to a new value. I tried using the label's own didSet, but it didn't work, as I was expecting. Is there a way to do this?

Upvotes: 1

Views: 411

Answers (2)

Adam
Adam

Reputation: 26917

it didn't work, as I was expecting

What do you mean by that? didSet works properly for overridden properties. Try this:

class MyLabel : UILabel {
    override var text : String? {
        didSet {
            resize()
        }
    }
    private func resize() {
        print("text is now \(text). resizing...")
        frame = CGRectMake(...
    }
}

Upvotes: 1

Serhii Mamontov
Serhii Mamontov

Reputation: 4932

Properties modification can be tracked using KVO. After your view, which has reference on target label will be initialised, you need to add add observer like this:

[self.label addObserver:self forKeyPath:@"text" 
                options:NSKeyValueObservingOptionNew context:nil];

In your view (same from which you called method above) you should have handler method like this:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                    change:(NSDictionary<NSString *,id> *)change 
                   context:(void *)context {

    // If you subscribed only for one value, you can resize from here or 
    // add conditions.
}

When you will leave view, don't forget to unsubscribe like this:

[self.label removeObserver:self forKeyPath:@"text" context:nil];

Warning: addObserver and removeObserver should be balanced. If you will call removeObserver extra time, your application will crash.

Upvotes: 0

Related Questions