2

Why is my color property always null?

@interface StreamingMediaControlButton : UIButton

@property (strong, nonatomic) UIColor *color;

@end

@implementation StreamingMediaControlButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _color = [UIColor whiteColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    NSLog(@"color: %@", self.color);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, self.color.CGColor);
}
@end
TijuanaKez
  • 1,472
  • 3
  • 20
  • 28

2 Answers2

3

Your previous comment said you are using interface builder, which means a different init method is invoked on the button. You need to implement:

- (id)initWithCoder:(NSCoder *)decoder
{
    if ((self = [super initWithCoder:decoder])) {
        // setup code
    }

    return self;
}

Quite often it's good practice to implement both initWithCoder: and initWithFrame: and have them both call a commonInit method where your shared setup code goes.

Mike Weller
  • 45,401
  • 15
  • 131
  • 151
  • Just the act of implementing initWithCoder seems to call initWithFrame via [super init]; – TijuanaKez Apr 25 '13 at 11:39
  • initWithCoder seems to reset the view's frame property. Is this supposed to happen? The idea is to place and size the objects view in interface builder. This happens even if initWithFrame is not overridden. – TijuanaKez Apr 25 '13 at 11:57
  • ....that would be because initWithCoder should call [super initWithCoder] not [super init]. Right. – TijuanaKez Apr 25 '13 at 12:22
0

Try to Use Color RGB value instead of directly defining color that would be more effective.

Mayur Prajapati
  • 5,454
  • 7
  • 41
  • 70
  • As it will be a reusable interface control, I wanted to stick with UIColors. Ideally the control's color property would be set to a the chosen UIColor, but default to white. – TijuanaKez Apr 25 '13 at 11:18