Nicolas Goy
Nicolas Goy

Reputation: 1430

Two way binding when setter is overriden

I have an NSTextField bound to some object "zoom" property.

In this object's class implementation, I have the following

- (void)setZoom:(CGFloat)zoom
{
    _zoom = MAX(0, MIN(10, zoom));
}

If I write "-5" in the textfield, setZoom: will be called with "-5" as argument and _zoom will be set to 0.

Then problem is that the textfield is not updating itself and it shows "-5" instead of re-reading the property value it has just set.

If I do myObject.zoom = -5; in code, the text field will display 0 correctly.

I tried to wrap _zoom =... inside willChangeValueForKey/didChangeValueForKey calls but it didn't change anything.

Upvotes: 1

Views: 195

Answers (1)

Marchenko Igor
Marchenko Igor

Reputation: 63

You can try to do in such way:

- (void)setZoom:(CGFloat)zoom
{
    CGFloat corectedValue = MAX(0, MIN(10, zoom));
    if (zoom != corectedValue)
    {
        [self setZoom:correctedValue];
    } else {
        _zoom = zoom;
    }
}

Upvotes: 1

Related Questions