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
Simply change
self.playButton.backgroundColor = [UIColor blackColor];
to
self.playButton.backgroundColor = [UIColor clearColor];
Just tested and it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With