ios - 向 UILabel 添加两个阴影

标签 ios objective-c uikit

我有一个 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;
}

有了这个,白色的影子出现了,但黑色的影子没有。

最佳答案

我不明白“一个 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;

但是你不能使用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;
 }

enter image description here

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

关于ios - 向 UILabel 添加两个阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32097527/

相关文章:

objective-c - 分配的对象的潜在泄漏 - 不知道为什么

ios - swift 和 UILabel : How to add padding and margin in Swift programmatically?

ios - 在 Swift 中使用引用设置 NSArray 实例

ios - 如何将 double 四舍五入到小数点后的第三位

iphone - 在没有 NSTimer 的情况下每隔几秒调用一次获取当前坐标

objective-c - UIScrollView setZoomScale 不起作用?

ios - UIPinchGestureRecognizer 仅用于捏合

ios - 在 Swift 中使用单例和解析 JSON

ios - 校准加速度计?

iphone - 初始化 2 个昏暗数组 NSMutableArray