I am trying to add a shadow to my UIViews using a custom extension that I created for the UIView class. Here is the code for the extension:
extension UIView {
func round(_ radius : CGFloat = 10) {
layer.cornerRadius = radius
clipsToBounds = true
}
func addBorder(color: UIColor, width: CGFloat) {
layer.borderColor = color.cgColor
layer.borderWidth = width
}
func addShadow(opacity: Float, size: Double, radius: Double, color: UIColor ) {
layer.shadowColor = color.cgColor
layer.shadowOpacity = opacity
layer.shadowOffset = CGSize(width: size, height: size)
layer.shadowRadius = radius
layer.masksToBounds = true
}
}
The round and addBorder functions work perfectly fine, but the addShadow function does not seem to be working. I have tried calling the function on a UIView instance like this:
let myView = UIView()
myView.addShadow(opacity: 0.5, size: 2, radius: 4, color: .black)
But the shadow does not show up on the view
I have tested this extension with other types of views, such as buttons and labels, and the shadow works perfectly fine. It seems to be a problem only with UIViews.
Does anyone know what might be causing this issue? Any help would be greatly appreciated. Thank you in advance
6
Answers
The issue may be caused by the
layer.masksToBounds = true
line in theaddShadow
function. This property clips the sublayers of the layer to the layer’s bounds, which could be preventing the shadow from being displayed.You can try setting
masksToBounds
to false before adding the shadow to the layer.yasir I have the same difficulty with shadows. I have solved it with this extension. Try it.
You can try by adding an UIBezierPath and by setting shouldRasterize = true.
layer.masksToBounds should be false to disables the layer’s mask to display the shadow outside of the view’s bounds.
By setting
layer.masksToBounds = true
, you are telling the view’s layer to clip any content that goes beyond its bounds, which would include the shadow you are trying to add.If that doesn’t work, you might want to try changing the backgroundColor attribute of the view to a color that isn’t translucent. If there is no content to render, the shadow won’t be seen since shadows are produced by displaying the content of the layer.
If we use clipsToBounds = true it will clip the frame and the shadow was cut off
just replace the line with clipsToBounds = false will fix it.
here is the modified code