Shadow UIview和clipsToBounds

Saf*_*ari 4 objective-c uikit uiview ios

我想将阴影设置为我的容器UIView.我使用此代码来实现:

- (id)initWithCoder:(NSCoder*)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {

        //-> drop shadow
        [self.layer setShadowColor:[UIColor blackColor].CGColor];
        [self.layer setShadowOpacity:0.6];
        [self.layer setShadowRadius:2.0];
        [self.layer setShadowOffset:CGSizeMake(2.0, 2.0)];
    }

    return self;
}
Run Code Online (Sandbox Code Playgroud)

这很好用.但是,当我_containerView.clipsToBounds = YES;在这个容器UIView上使用时,我看不到我的影子.为什么?

Gad*_*Gad 26

clipsToBounds还夹你的影子.为了防止这种情况,您可以添加_containerView.layer.masksToBounds = NO禁用子层的剪切(请参阅此处).

  • 感谢`masksToBounds` (2认同)

Lex*_* Li 5

如果您clipsToBounds = true因为不想让子视图超出视图的边框而不得不使用,但同时又需要视图上的阴影,我建议在视图后面添加一个额外的视图,并在额外的视图上设置阴影属性。

//run this in viewDidLoad() or your initialisation code
private func setupShadowContainer() {
    let containerShadow = UIView()
    parentView.addSubview(containerShadow)
    containerShadow.dropShadow()
    //using SnapKit here, you can use NSLayoutConstraint in a similar way to constraint the containerShadow behind your View
    containerShadow.snp.makeConstraints { (make) in
        make.edges.equalTo(yourView.snp.edges)
    }
}

//dropShadow method
extension UIView {
    func dropShadow() {
        self.translatesAutoresizingMaskIntoConstraints = false
        self.layer.shadowRadius = 3
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
        self.layer.shadowOpacity = 0.5
        self.layer.masksToBounds = false
    }
}
Run Code Online (Sandbox Code Playgroud)