nickw444
nickw444

Reputation: 966

CAGradientLayer behind self.layer appearing above

I'm trying to make a custom UIButton class, except, when drawing the background of the button, and adding it as a sublayer using insertSubLayer behind: method, it still appears infront of the UIButton Textlabel.

My code is posted below, Any help would be greatly appreciated.

CALayer *layer = self.layer;

layer.cornerRadius = 3.0f;
layer.masksToBounds = YES;
layer.borderWidth = 1.0f;
layer.borderColor = [UIColor colorWithWhite:0.5f alpha:0.5f].CGColor;
self.titleLabel.textColor = [UIColor greenColor];
//layer.backgroundColor = [UIColor greenColor].CGColor;

bgColor = [CAGradientLayer layer];
bgColor.frame = self.layer.bounds;
self.backgroundColor = [UIColor colorWithWhite:1 alpha:1];
bgColor.colors = [NSArray arrayWithObjects:
                     (id)[UIColor colorWithWhite:0.97f alpha:1].CGColor,
                     (id)[UIColor colorWithWhite:0.87f alpha:1].CGColor,
                     nil];
bgColor.locations = [NSArray arrayWithObjects:
                        [NSNumber numberWithFloat:0.0f],
                        [NSNumber numberWithFloat:1],
                        nil];
[self.layer addSublayer:bgColor];
[self.layer insertSublayer:bgColor below:layer];

Upvotes: 1

Views: 1064

Answers (1)

jrturton
jrturton

Reputation: 119242

self.layer and layer in your code point to the same object. You're asking the layer to insert a sublayer behind itself - this is not possible. Sublayers are contained within the parent layer. Try

[self.layer insertSublayer:bgColor atIndex:0];

Instead of

[self.layer addSublayer:bgColor]; 
[self.layer insertSublayer:bgColor below:layer];

This will add the gradient at the lowest possible point in the layer hierarchy of your button.

Upvotes: 2

Related Questions