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?
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
}
}
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).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With