Search code examples
objective-ciosiboutletiboutletcollection

IBOutletCollection and initializing Custom Class Instance


I am using the MHRotaryKnob Class and having trouble configuring it so that multiple outlets have the same default settings. It is no problem to get it working with one instance using IBOutlet, but now it is looking for the properties of the MHRotaryKnob class in NSArray.

How exactly do I define rotaryKnob in the implementation so that the settings are relayed to all controls hooked up to IBOutletCollection? The properties in the implementation are defined in MHRotaryKnob.m but now the compiler is looking for it in NSArray.

ViewController.h

#import <UIKit/UIKit.h>
#import "MHRotaryKnob.h"

@interface CBViewController : UIViewController

@property (nonatomic, retain) IBOutletCollection (MHRotaryKnob) NSArray *rotaryKnob;

ViewController.m

#import "ViewController.h"
#import "MHRotaryKnob.h"


@implementation CBViewController;

@synthesize rotaryKnob;


- (void)viewDidLoad
{
[super viewDidLoad];

rotaryKnob.interactionStyle = MHRotaryKnobInteractionStyleSliderVertical;
rotaryKnob.scalingFactor = 1.5f;
rotaryKnob.defaultValue = rotaryKnob.value;
rotaryKnob.resetsToDefault = YES;
rotaryKnob.backgroundColor = [UIColor whiteColor];
rotaryKnob.backgroundImage = [UIImage imageNamed:@"knob_passive.png"];
[rotaryKnob setKnobImage:[UIImage imageNamed:@"knob_passive.png"] forState:UIControlStateNormal];
[rotaryKnob setKnobImage:[UIImage imageNamed:@"knob_highlighted.png"] forState:UIControlStateHighlighted];
[rotaryKnob setKnobImage:[UIImage imageNamed:@"Knob Disabled.png"] forState:UIControlStateDisabled];
rotaryKnob.knobImageCenter = CGPointMake(35.0f, 32.0f);
[rotaryKnob addTarget:self action:@selector(rotaryKnobDidChange) forControlEvents:UIControlEventValueChanged];

Solution

  • An IBOutletCollection is a collection hence why it is backed by an NSArray in this case.

    So it might help to rename the ivar to rotaryKnobs to make this fact clear and then use it like this

    for (MHRotaryKnob *rotaryKnob in self.rotaryKnobs) {
        rotaryKnob.interactionStyle = MHRotaryKnobInteractionStyleSliderVertical;
        rotaryKnob.scalingFactor    = 1.5f;
        rotaryKnob.defaultValue     = rotaryKnob.value;
        rotaryKnob.resetsToDefault  = YES;
        rotaryKnob.backgroundColor  = [UIColor whiteColor];
        rotaryKnob.backgroundImage  = [UIImage imageNamed:@"knob_passive.png"];
        rotaryKnob.knobImageCenter  = CGPointMake(35.0f, 32.0f);
        [rotaryKnob setKnobImage:[UIImage imageNamed:@"knob_passive.png"]     forState:UIControlStateNormal];
        [rotaryKnob setKnobImage:[UIImage imageNamed:@"knob_highlighted.png"] forState:UIControlStateHighlighted];
        [rotaryKnob setKnobImage:[UIImage imageNamed:@"Knob Disabled.png"]    forState:UIControlStateDisabled];
        [rotaryKnob addTarget:self action:@selector(rotaryKnobDidChange) forControlEvents:UIControlEventValueChanged];
    }