Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shadow UIview and clipsToBounds

I would like to set the shadow to my container UIView. I use this code to make it:

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

This works well. But, when I use _containerView.clipsToBounds = YES; on this container UIView, I can't see my shadow. Why?

like image 520
Safari Avatar asked May 20 '14 13:05

Safari


3 Answers

If you have to use clipsToBounds = true because you don't want subviews to exceed your view's border, but at the same time you need a shadow on your view, I recommend adding an extra view behind your view and set the shadow properties on the extra view.

//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
    }
}
like image 85
Lexon Li Avatar answered Oct 26 '22 13:10

Lexon Li


the clipsToBounds also clips your shadow. In order to prevent this you can add _containerView.layer.masksToBounds = NO which disables clipping of sublayers (see more here).

like image 29
Gad Avatar answered Oct 26 '22 11:10

Gad


Here is the UIView extension.

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

Call this function after creation of view as follows:

let roundView = UIView()
roundView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 100)
roundView.addShadowAndRoundCorner(cornerRadius: 100/2)
like image 24
Shubham Daramwar Avatar answered Oct 26 '22 11:10

Shubham Daramwar