Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add CAGradientLayer to UIButton

I am trying to modify a button's look and spent a long while trying to figure out why I can not apply a gradient to it like with this simple code below:

[self.playButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
self.playButton.backgroundColor = [UIColor blackColor];

CAGradientLayer *gradient = [[CAGradientLayer alloc] init];
gradient.frame = self.playButton.bounds;
gradient.position = CGPointMake(self.playButton.bounds.size.width/2, self.playButton.bounds.size.height/2);
gradient.colors = [NSArray arrayWithObjects:
                   (id)[UIColor greenColor].CGColor,
                   (id)[UIColor redColor].CGColor,
                   nil];
gradient.locations = [NSArray arrayWithObjects:
                      [NSNumber numberWithFloat:0.0f],
                      [NSNumber numberWithFloat:1.0f],
                      nil];

[self.playButton.layer addSublayer:gradient];

It executes, but nothing happens. I know the code ought to work, because many other use it and when changing the self.playButton to say self.view then it adds a beautiful red-green gradient layer to the UIView.

It may be worth noting that I the custom button is defined as an IBOutlet like this:

@property (weak, nonatomic) IBOutlet UIButton *playButton;

Any help is greatly appreciated.

UPDATE & FIX

When changing the button to use a scalable image instead of a gradient, I forgot to re-comment-out the gradient code (after trying rokjarc's idea) and when changing the button's imageView.content to UIViewContentModeScaleToFill the gradient displayed...

self.playButton.imageView.contentMode = UIViewContentModeScaleToFill;

So thanks rokjarc I suppose :D

like image 516
Max Z. Avatar asked Nov 25 '25 18:11

Max Z.


1 Answers

Simply change

self.playButton.backgroundColor = [UIColor blackColor];

to

self.playButton.backgroundColor = [UIColor clearColor];

Just tested and it works.

like image 149
Rok Jarc Avatar answered Nov 28 '25 07:11

Rok Jarc