I am trying to round the top two corners of a UIView and add a shadow above this view using a UIView extension. However the solution I came up with isn’t working. When I use the following solution the shadow only appears in the rounded corners and not above the view where I want it.
extension UIView {
func roundCornersWithShadow(_ corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
layer.mask = mask
mask.path = path.cgPath
mask.shadowColor = UIColor.black.cgColor
mask.shadowPath = mask.path
mask.shadowOffset = CGSize(width: 0.0, height: -2.0)
mask.shadowOpacity = 0.9
mask.shadowRadius = 3
layer.masksToBounds = false
}
}
4
Answers
SWIFT 5: iOS 11 introduced
maskedCorners
which results in smoother and better quality results. You can still use theUIRectCorner
in the function call and have it translated toCACornerMask
:These functions need to be applied in layoutSubviews() of your superview.
[SWIFT-5] iOS 11 introduced maskedCorners which results in smoother and better quality results. You can still use the UIRectCorner in the function call and have it translated to CACornerMask:
}
You can use this extension: