Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shadow on UIButton text only (not background)

I have a set of UIButtons with background colors. when the user taps one, I want only the button's text to have a shadow all around it (to show that it has been selected). However, when I add the shadow, the shadow appears over the whole button (background and all), and not just the text. Is there an easier workaround to this than just adding a UILabel over a blank button?

UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
...
[button setBackgroundColor:[UIColor blueColor]];

[button.layer setShadowRadius:8.0];
[button.layer setShadowColor:[[UIColor orangeColor] CGColor]];
[button.layer setShadowOpacity:0];
...
like image 775
ricky3350 Avatar asked Oct 25 '25 06:10

ricky3350


1 Answers

Here is the simple way to add shadow to the button title with shadow radius property available in Objective-C:

#import <QuartzCore/QuartzCore.h>    

button.titleLabel.layer.shadowOffset = CGSizeMake(2.0, 2.0);
button.titleLabel.layer.shadowColor = [UIColor colorWithWhite:0.1 alpha:0.7].CGColor;
button.titleLabel.layer.shadowRadius = 2.0;
button.titleLabel.layer.shadowOpacity = 1.0;
button.titleLabel.layer.masksToBounds = NO;

Swift ..

Say you override the UIButton class ..

    titleLabel!.layer.shadowColor = UIColor.black.cgColor
    titleLabel!.layer.shadowOffset = CGSize(width: -0.5, height: 0.5)
    titleLabel!.layer.shadowOpacity = 1.0
    titleLabel!.layer.shadowRadius = 0
    titleLabel!.layer.masksToBounds = false
like image 53
Userich Avatar answered Oct 27 '25 20:10

Userich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!