仅 UIButton 文本上的阴影(不是背景)

Shadow on UIButton text only (not background)

我有一组带有背景颜色的 UIButton。当用户点击一个按钮时,我希望 按钮的文本周围有一个阴影(以表明它已被选中)。但是,当我添加阴影时,阴影会出现在整个按钮(背景和所有按钮)上,而不仅仅是文本。有没有比在空白按钮上添加 UILabel 更简单的解决方法?

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

[button.layer setShadowRadius:8.0];
[button.layer setShadowColor:[[UIColor orangeColor] CGColor]];
[button.layer setShadowOpacity:0];
...

只是在 UIButtontitleLabel 属性 上设置阴影,而不是你现在正在做的。

例如

button.titleLabel.shadowColor = ((selectionState) ?[UIColor orangeColor] : [UIColor clearColor] );
button.titleLabel.shadowOffset = CGSizeMake (1.5,1.5);

2018 年

这不起作用。使用@Userich

的回答

实现此目的的一种方法是对普通标题和突出显示的标题使用属性字符串。您可以创建 NSShadow object,并将其指定为 NSShadowAttributeName 的值。这使您可以控制阴影的属性。为了防止标题变暗,您应该将按钮类型设置为 Custom 而不是 System

- (void)viewDidLoad {
    [super viewDidLoad];

    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowColor = [UIColor darkGrayColor];
    shadow.shadowOffset = CGSizeMake(2, 2);
    shadow.shadowBlurRadius = 2;

    NSString *titleString = @"Title";
    NSAttributedString *normalTitle = [[NSAttributedString alloc] initWithString:titleString];
    NSAttributedString *highlightedTitle = [[NSAttributedString alloc] initWithString:titleString attributes:@{NSShadowAttributeName:shadow}];

    [self.button setAttributedTitle:normalTitle forState:UIControlStateNormal];
    [self.button setAttributedTitle:highlightedTitle forState:UIControlStateHighlighted];
}

您需要使用 setTitleShadowColor: forState:shadowOffset 属性 of UIButton. 每当用户点击按钮时,下面的代码将仅向按钮标签添加阴影。

UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];

[button setBackgroundColor:[UIColor blueColor]];

button.frame = CGRectMake(50, 70, 200, 100);

[button setTitle:@"Test Button" forState:UIControlStateNormal];

[button.titleLabel setFont:[UIFont systemFontOfSize:45]];

[button setTitleShadowColor:[UIColor redColor] forState:UIControlStateHighlighted];

[button.titleLabel setShadowOffset:CGSizeMake(2.0, 2.0)];

希望这会有所帮助。

这是向按钮标题添加阴影的简单方法,阴影半径 属性 在 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 ..

假设您覆盖了 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