1

I have implemented a UIView with rounded rect only at the top left and top right corners using UIBezierPath. But after that when i add a shadow to the view, it doesn't show the shadow. If i just remove the bezier rounded corners, then the shadow works perfectly fine. But now only the rounded corners appear without any shadow. Here's my code

override func drawRect(rect: CGRect)
{
    super.drawRect(rect)

    let shapeLayer : CAShapeLayer = CAShapeLayer(layer: centerView.layer)
    shapeLayer.path = UIBezierPath(roundedRect: centerView.layer.bounds, byRoundingCorners: UIRectCorner.TopRight|UIRectCorner.TopLeft, cornerRadii: CGSizeMake(15,15)).CGPath
    centerView.layer.mask = shapeLayer

    centerView.layer.masksToBounds = false

    centerView.layer.shadowOffset = CGSizeMake(0,-2)
    centerView.layer.shadowRadius = 0.5
    centerView.layer.shadowOpacity = 0.7
    centerView.layer.shadowColor = UIColor(red: 0.867, green: 0.867, blue: 0.867, alpha: 1).CGColor
    centerView.layer.shadowPath =  UIBezierPath(roundedRect: centerView.layer.bounds, byRoundingCorners: UIRectCorner.TopRight|UIRectCorner.TopLeft, cornerRadii: CGSizeMake(15,15)).CGPath
}

Here i override the drawRect of a UITableViewCell and centerView is a subview of it. Also i tried subclassing UIView for centerView, that too doesn't seem to work.

Does the mask property and maskToBounds property of a CALayer conflict with each other ?

  • why are you doing this in drawRect? You are not even using the `rect` variable - this kind of stuff should be done in `layoutSubviews`. At least the **layout**. Creating layers should be done during initial setup - you should not create a new layer every draw call. – luk2302 Jul 22 '15 at 08:19
  • ok. But that doesn't solve the issue. Still the problem remains – Mohammed Shinoys Jul 22 '15 at 09:00

1 Answers1

7

Once you apply a masking layer to a view, that view will be clipped to the masking layer. The view's shadow will also be clipped, so it will not be drawn. A common solution to this problem is to have 2 views. One view is for casting a shadow and the other one is for masking. In your case, centerView is the masking view, since you set the masking layer to the centerView layer. What you need to do is create a new view, let's call it containerView. Add the centerView to containerView, and set the shadow on the container view instead of centerView.

MaxK
  • 625
  • 7
  • 18