user717452
user717452

Reputation: 111

Subclass of UIButton not Working

I have an app in which I am going to need multiple labels to write text on the button which will change each day. To do this, I am setting up a subclass of UIButton but am having difficulties. My implementation for the subclass looks like this:

@implementation GlossyButton


- (id)initWithFrame:(CGRect)frame withBackgroundColor:(UIColor*)backgroundColor
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self makeButtonShiny:self withBackgroundColor:backgroundColor];
    }
    return self;
}

- (void)makeButtonShiny:(GlossyButton*)button withBackgroundColor:(UIColor*)backgroundColor
{
    // Get the button layer and give it rounded corners with a semi-transparant button
    UIColor *bobcatred = [UIColor whiteColor];

    CALayer* l = button.layer;

    CAGradientLayer *shineLayerl = [CAGradientLayer layer];
    shineLayerl.frame = l.bounds;
    shineLayerl.colors = [NSArray arrayWithObjects:
                          (id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                          (id)[UIColor colorWithWhite:1.0f alpha:0.2f].CGColor,
                          (id)[UIColor colorWithWhite:0.75f alpha:0.2f].CGColor,
                          (id)[UIColor colorWithWhite:0.4f alpha:0.2f].CGColor,
                          (id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                          nil];
    shineLayerl.locations = [NSArray arrayWithObjects:
                             [NSNumber numberWithFloat:0.0f],
                             [NSNumber numberWithFloat:0.5f],
                             [NSNumber numberWithFloat:0.5f],
                             [NSNumber numberWithFloat:0.8f],
                             [NSNumber numberWithFloat:1.0f],
                             nil];

    [l setMasksToBounds:YES];
    [l setCornerRadius:11];
    [l setBorderWidth:2.0];
    [l setBorderColor: [bobcatred CGColor]];
    [l addSublayer:shineLayerl];
    // Add the layer to the button
    [button.layer addSublayer:shineLayerl];

    [button setBackgroundColor:[UIColor redColor]];
}

@end

I don't add in the labels yet, just checking that it will draw everything properly.

I then go to the ViewController where this will be and add an IBOutlet property for the button. In storyboard, I drag a UIButton onto the view, change its type on property to custom, and in class I change it from UIButton to GlossyButton. I then run it, but it just has a blank spot in the app without any of the Gradients, border, or anything. What am I doing incorrectly?

Upvotes: 1

Views: 340

Answers (1)

auspicious99
auspicious99

Reputation: 4311

For a custom UIButton subclass instantiated from a storyboard, initWithFrame will not be called. Try initWithCoder instead.

Upvotes: 3

Related Questions