TijuanaKez
TijuanaKez

Reputation: 1472

How to properly use a UIColor as a property

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

Upvotes: 2

Views: 2665

Answers (2)

Mike Weller
Mike Weller

Reputation: 45598

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.

Upvotes: 3

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

Upvotes: 0

Related Questions