Programmatically adding a shadow to a UIButton label

前端 未结 6 563
盖世英雄少女心
盖世英雄少女心 2021-02-04 03:15

I\'m trying to add a 1px black drop shadow to a button label with no luck. I\'ve tried this:self.setTitleShadowOffset = CGSizeMake(0, -1); but I get:

相关标签:
6条回答
  • 2021-02-04 04:03

    The right property is 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);
    
    0 讨论(0)
  • 2021-02-04 04:08

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

    #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;
    
    0 讨论(0)
  • 2021-02-04 04:12

    for Swift 3:

      button.setTitleShadowColor(UIColor.red, for: .normal)
      button.titleLabel?.shadowOffset = CGSize(width: 2, height: 2)
    
    0 讨论(0)
  • 2021-02-04 04:14

    The other answers do not properly set the shadow color (I suspect they didn't notice because they were trying to set the shadow color to what it is by default, black.)

    This code worked for me to add a white shadow to the text of my button:

    myButton.titleLabel.shadowOffset = CGSizeMake(0, 1);
    [myButton setTitleShadowColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    0 讨论(0)
  • 2021-02-04 04:14

    In 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
    

    0 讨论(0)
  • 2021-02-04 04:17

    The setTitleShadowOffset for UIButton is deprecated. Use the shadowOffset of titleLabel property of UIButton

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

    0 讨论(0)
提交回复
热议问题