Shadow UIview和clipsToBounds

时间:2014-05-20 13:16:14

标签: ios objective-c uiview uikit

我想将阴影设置为我的容器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;
}

这很有效。但是,当我在这个容器UIView上使用_containerView.clipsToBounds = YES;时,我无法看到我的影子。为什么呢?

4 个答案:

答案 0 :(得分:23)

clipsToBounds也剪辑你的影子。为了防止这种情况,您可以添加_containerView.layer.masksToBounds = NO来禁用子图层裁剪(请参阅更多here)。

答案 1 :(得分:2)

如果由于不希望子视图超出视图的边界而必须使用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
    }
}

答案 2 :(得分:0)

这是UIView扩展。

extension UIView {
    func addShadowAndRoundCorner(cornerRadius : CGFloat) {
        self.layer.shadowOffset = .zero
        self.layer.shadowOpacity = 0.5
        self.layer.shadowRadius = 3
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.masksToBounds = false
        self.layer.cornerRadius = cornerRadius
    }
}

在创建视图后按如下所示调用此函数:

let roundView = UIView()
roundView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 100)
roundView.addShadowAndRoundCorner(cornerRadius: 100/2)

答案 3 :(得分:-1)

- (void)layoutSubviews
{
    [super layoutSubviews];

    CAGradientLayer *l = [CAGradientLayer layer];
    l.frame = self.bounds;
    l.colors = [NSArray arrayWithObjects:(id)[UIColor clearColor].CGColor, (id)[UIColor whiteColor].CGColor, (id)[UIColor whiteColor].CGColor,(id)[UIColor whiteColor].CGColor,(id)[UIColor whiteColor].CGColor,(id)[UIColor whiteColor].CGColor, (id)[UIColor clearColor].CGColor,(id)[UIColor clearColor].CGColor, nil];
    l.startPoint = CGPointMake(0.0f, 1.0f);
    l.endPoint = CGPointMake(1.0f, 1.0f);
    self.layer.mask = l;
}