为UILabel添加两个阴影

3

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

一个是黑色的阴影,另一个是白色的阴影。

一个阴影的y偏移量为-1,另一个阴影的y偏移量为1。

- (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;
}

这样白色的阴影就会出现,但黑色的则不会。


嘿,你想给标签文本或标签视图添加两个阴影吗? - Joe Hallenbeck
我想要给这段文字添加两个阴影。 - Tiago Veloso
1个回答

2
我不明白你所说的“将两个阴影添加到UILabel”是什么意思,但我希望我可以帮忙。如果在这张图片上你能看到你想要的东西,我会很高兴 :)

enter image description here

- (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;

但是你不能使用两个阴影属性,只能使用一个。而且你可以自定义。
 -(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;
 }

enter image description here

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

我认为你指引了我正确的方向。你能否给NSAttributedString添加不同的阴影? - Tiago Veloso
我已经删除了第二个问题。 - Joe Hallenbeck
@TiagoVeloso 完成 - Joe Hallenbeck
你的回答确实解决了我的问题,但我想知道是否可以使用两个CALayer来完成? - Tiago Veloso

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接