Meltemi Meltemi - 5 months ago 13
Objective-C Question

Override UILabel's setText method?

I'd like to override

UILabel
's
setText
method but I'm not sure that:

A) it's possible, and

B) if maybe there's a better way to achieve what I'm trying to accomplish.

I have a subclass of
UIView
that has a
UILabel
property as one of its sub-views. I'd like to know when the
UILabel
's "text" property changes so I can adjust the size of the rounded rect behind it. If I owned
UILabel
I'd just override
setText
...but
UILabel
is Apple's and its implementation is hidden.

So, how should I be going about this?

Answer

You can use Key-Value Observing to track changes to the UILabel.text property. The approach involves three steps:

1) Registering to observe the property, when you load the view

[label addObserver:inspector
             forKeyPath:@"text"
                 options:(NSKeyValueObservingOptionNew |
                            NSKeyValueObservingOptionOld)
                    context:NULL];

2) Receiving a notification about any changes:

- (void)observeValueForKeyPath:(NSString *)keyPath
              ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if ([keyPath isEqual:@"text"]) {
        // put your logic here
    }
    // be sure to call the super implementation
    // if the superclass implements it
    [super observeValueForKeyPath:keyPath
                ofObject:object
                 change:change
                 context:context];
}

3) De-registering the observation whenever you aren't interested any more:

[label removeObserver:inspector forKeyPath:@"text"];