Monday 16 August 2010

Key Value Observing and UISliders

Using Key Value Coding can be a huge code saver! Having been looking into this lately, I got rather excited.

Unfortunately UIKit controls aren't actually KVO compliant.  To track changes to their value, you have to handle the Value Changed event.

To get around this, create a new class to derive from UISlider.

I added a property that could be observed. Then in the init method, setup the event which will capture the changes to the value and broadcast them to the property and any one doing their Key Value Observing.

The header is simple :


@interface KeyValueSlider : UISlider {
}

@property int kvValue;
@end



And the implementation :


#import "KeyValueSlider.h"

@implementation KeyValueSlider

-(id) initWithFrame: (CGRect) frame {
    if (self = [super initWithFrame: frame]) {

            [self addTarget: self
                          action: @selector(valueChanged:)          
        forControlEvents: UIControlEventValueChanged];
    }

    return self;
}

- (void)valueChanged: (UISlider *) control {
    self.kvValue = control.value;
}

-(int) kvValue {
    return self.value;
}

-(void) setKvValue : (int) value {
    // Do nothing, this is just for observing.
}

@end

Then just observe the "kvValue" property.

Works a beaut!