When you add a mask to a layer, it grips anything outside of that mask, including the shadow. To achieve this, you need to add a βshadowβ view below your masked view, which has the same path as the mask.
Or add a shadow layer to the hidden superview
.
let view = UIView(frame: CGRect(x: 50, y: 70, width: 100, height: 60)) view.backgroundColor = .cyan let mask = CAShapeLayer() mask.path = UIBezierPath(roundedRect: view.bounds, cornerRadius: 10).cgPath view.layer.mask = mask let shadowLayer = CAShapeLayer() shadowLayer.frame = view.frame shadowLayer.path = UIBezierPath(roundedRect: view.bounds, cornerRadius: 10).cgPath shadowLayer.shadowOpacity = 0.5 shadowLayer.shadowRadius = 5 shadowLayer.masksToBounds = false shadowLayer.shadowOffset = .zero let container = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) container.backgroundColor = .white container.layer.addSublayer(shadowLayer) container.addSubview(view)
If you intend to use it elsewhere, you can create a ShadowMaskedView
that contains the shadow layer, and a hidden view - possibly with the path property.
source share