1

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];
2
  • Where is this code in your button class?
    – jrturton
    Jul 31, 2012 at 11:00
  • It runs on InitWithFrame
    – nickw444
    Jul 31, 2012 at 11:02

1 Answer 1

2

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.

1
  • You're a lifesaver. Worked first go. Thankyou very much. Saved me much headache.
    – nickw444
    Jul 31, 2012 at 11:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.