阴影未显示在UIView上

11

我有一个ViewController,在这个控制器中有两个UIView。

我想在第一个UIView底部添加阴影,该阴影显示在第二个UIView上。

first UIView

-------------
              <- shadow here
secondUIView

但是当我仅仅添加这段代码时,它并没有起作用。
 firstView.layer.masksToBounds = true
 firstView.layer.shadowOffset = CGSizeMake(0,5)
 firstView.layer.shadowOpacity = 0.5
 firstView.layer.shadowPath = UIBezierPath(rect: firstView.bounds).CGPath

2
检查 shadowOpacity,它默认为0。 - onmyway133
5个回答

37

如果你将maskToBounds设置为false,它应该显示阴影。

firstView.layer.masksToBounds = false

如果masksToBounds属性为true,则超出视图边界的任何内容都将被裁剪到这些边界。


@ThirdMartian 嗯...我不知道...可能是其他问题...我按照你发布的代码运行了一遍。我只把 true 改成了 false,并将阴影偏移设置为 CGSizeMake(0, 25),这样我就可以清楚地看到阴影了。它起作用了。 - euvs
我不得不改变故事板中的顺序,无论如何,感谢您的帮助! - user5762284
2
@ThirdMartian 这可能已经太晚了,但对于未来的人来说,“firstView.clipsToBounds = false”也是必要的,以防之前设置为“true”。 - B L

16
如果你有两个视图 view1view2,且view2 就在view1的下方,它可能会覆盖view1的阴影。当view2被添加为view1后的子视图时,就会发生这种情况。
在添加view2之后将view1作为子视图添加,或在某些时候调用[superview bringSubviewToFront:view1]

3
读到这个问题后,我终于明白了它的简单和显而易见。谢谢。 - Matt Robinson

6

Swift 4.2

extension UIView {
    
    public func addShadowToView(shadow_color: UIColor,offset: CGSize,shadow_radius: CGFloat,shadow_opacity: Float,corner_radius: CGFloat) {
        self.layer.shadowColor = shadow_color.cgColor
        self.layer.shadowOpacity = shadow_opacity
        self.layer.shadowOffset = offset
        self.layer.shadowRadius = shadow_radius
        self.layer.cornerRadius = corner_radius
    }
}

将函数这样调用:

firstView.addShadowToView(shadow_color: UIColor.black, offset: CGSize(width: 0, height: 5), shadow_radius: 5.0, shadow_opacity: 0.5, corner_radius: 0.0)

同时请确保以下内容:

  • view clipsToBounds property is false

    firstView.clipsToBounds = false
    
  • firstView backgroundColor should not be clear color

    firstView.backgroundColor = UIColor.white
    

2

移除firstView.layer.masksToBounds = true,因为它将导致您的视图裁剪掉阴影,因为它从技术上讲超出了其范围。

此外,如果您只想要一个跟随视图形状的普通阴影,也可以移除firstView.layer.shadowPath = UIBezierPath(rect: firstView.bounds).CGPath.


0

masksToBounds = true会导致阴影被隐藏。 解决方法之一是在第一个视图下面添加一个阴影视图:

UIView *shadowView = [UIView new];
shadowView.frame = firstView.frame;
shadowView.layer.shadowOffset = CGSizeMake(0, 5);
shadowView.layer.shadowOpacity = 0.5
shadowView.layer.shadowPath = UIBezierPath(rect: shadwoView.bounds).CGPath;
[self.view insertSubview:shadowView belowSubview:firstView];

1
不要忘记添加shadowRadiusshadowColor - Xiao.Li

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