Search code examples
iosobjective-ccocoa-touchuibuttonshadow

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];
...

Solution

  • 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