以编程方式将阴影添加到UIButton标签

时间:2011-03-03 09:36:22

标签: ios uibutton ios-4.2

我正在尝试在没有运气的情况下为按钮标签添加1px黑色阴影。我试过这个:self.setTitleShadowOffset = CGSizeMake(0, -1);但是我得到了:

  

在非结构或联合的内容中请求成员'setTitleShadowOffset'

任何建议都会非常棒,谢谢!

6 个答案:

答案 0 :(得分:38)

正确的属性是self.titleLabel.shadowOffset:

UIButton *b = [UIButton buttonWithType:UIButtonTypeRoundedRect];    
[b setTitleShadowColor:[UIColor purpleColor] forState:UIControlStateNormal];
b.titleLabel.shadowOffset = CGSizeMake(1.0, 1.0);
[b setTitle:@"Hello, I'm a Button" forState:UIControlStateNormal];
b.frame = CGRectMake(10.0, 10.0,300.0, 40.0);

答案 1 :(得分:21)

其他答案没有正确设置阴影颜色(我怀疑他们没有注意到,因为他们试图将阴影颜色设置为默认颜色,黑色。)

此代码可以让我在按钮文本中添加白色阴影:

myButton.titleLabel.shadowOffset = CGSizeMake(0, 1);
[myButton setTitleShadowColor:[UIColor whiteColor] forState:UIControlStateNormal];

答案 2 :(得分:10)

setTitleShadowOffset UIButton已弃用。使用shadowOffset

的title UIButton titleLabel属性

buttonName.titleLabel.shadowOffset = CGSizeMake(0, -1);

答案 3 :(得分:7)

在Swift 3.0中

myButton.titleLabel?.layer.shadowRadius = 3
myButton.titleLabel?.layer.shadowColor = UIColor.black.cgColor
myButton.titleLabel?.layer.shadowOffset = CGSize(width: 0, height: 1)
myButton.titleLabel?.layer.shadowOpacity = 0.5
myButton.titleLabel?.layer.masksToBounds = false

enter image description here

答案 4 :(得分:0)

对于Swift 3:

  button.setTitleShadowColor(UIColor.red, for: .normal)
  button.titleLabel?.shadowOffset = CGSize(width: 2, height: 2)

答案 5 :(得分:0)

以下是如何使用radius属性在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;