向 UILabel 添加两个阴影

Adding two shadows to a UILabel

我有一个 UILabel 想要添加两个阴影。

一个黑色的影子,一个白色的影子。

一个有 -1 y 偏移,另一个有 1 个 y 偏移。

- (void)layoutSubviews{
    [super layoutSubviews];

    self.sectionTitleLabel.layer.shadowColor = [[UIColor whiteColor] CGColor];
    self.sectionTitleLabel.layer.shadowRadius = 0.0f;
    self.sectionTitleLabel.layer.shadowOpacity = .2;
    self.sectionTitleLabel.layer.shadowOffset = CGSizeMake(0.f, -1.f);

    CALayer *blackShadow = [[CALayer alloc] initWithLayer:self.sectionTitleLabel.layer];

    blackShadow.shadowColor = [[UIColor blackColor] CGColor];
    blackShadow.shadowRadius = 0.0f;
    blackShadow.shadowOpacity = .4;
    blackShadow.shadowOffset = CGSizeMake(0.f, 1.f);
    [self.sectionTitleLabel.layer addSublayer:blackShadow];

    self.sectionTitleLabel.layer.masksToBounds = NO;
}

这样白影出现,黑影不出现

我不明白 "two shadows to a UILabel" 是什么意思,但希望能帮到您。如果在这张照片上你能看到你想要的,我会很高兴:)

- (void)viewDidLoad
{
   [super viewDidLoad];

   NSMutableAttributedString* attString = [[NSMutableAttributedString alloc] initWithString:self.custLabel.text];
   NSRange range = NSMakeRange(0, [attString length]);

   [attString addAttribute:NSFontAttributeName value:self.custLabel.font range:range];
   [attString addAttribute:NSForegroundColorAttributeName value:self.custLabel.textColor range:range];

   NSShadow* shadow = [[NSShadow alloc] init];
   shadow.shadowColor = [UIColor whiteColor];
   shadow.shadowOffset = CGSizeMake(0.0f, 1.0f);
   [attString addAttribute:NSShadowAttributeName value:shadow range:range];

   self.custLabel.attributedText = attString;

   [self nextShadow];

}

 -(void)nextShadow
 {
     self.custLabel.layer.masksToBounds = NO;
     self.custLabel.layer.cornerRadius = 5; 
     self.custLabel.layer.shadowOffset = CGSizeMake(3, 0);
     self.custLabel.layer.shadowRadius = 5;
     self.custLabel.layer.shadowOpacity = 1.5;
 }

我会尝试使用

 - (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;

但是你不能使用2个影子属性,只能使用一个。您可以自定义

 -(void)nextShadow

创建好的解决方案的方法,例如

 -(void)nextShadow
 {
     self.custLabel.layer.masksToBounds = NO;
     self.custLabel.layer.cornerRadius = 1;
     self.custLabel.layer.shadowOffset = CGSizeMake(1, 0);
     self.custLabel.layer.shadowRadius = 1;
     self.custLabel.layer.shadowOpacity = 1.5;
 }

如果你调整 -(void)nextShadow 中的值,你可以得到你想要的。