UIView with corner Radius and Shadow view doesn't clip subviews in corners
The way you were trying to implement a second view to handle shadows is almost correct, you just didn't keep the right order.
Your CardView
class already handles displaying a shadow. Leave that view as it is and instead add a UIView called "ContentView
" as a subview. That content view has the same frame and corner radius as your CardView.
On the "ContentView
", you don't need to do any work with shadows. Instead, set its layer's masksToBounds
property to true
. Now add all the content you want to display in your Card to the "ContentView
" and it should clip correctly.
func commonInit() {
layer.cornerRadius = cornerRadius
let shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)
layer.masksToBounds = false
layer.shadowColor = shadowColor?.cgColor
layer.shadowOffset = CGSize(width: shadowOffsetWidth, height: shadowOffsetHeight)
layer.shadowOpacity = shadowOpacity
layer.shadowPath = shadowPath.cgPath
let contentView = UIView()
contentView.frame = self.frame
contentView.layer.cornerRadius = cornerRadius
contentView.layer.masksToBounds = true
// any content you add should now be added to the contentView:
// contentView.addSubview(aView)
}