Shadow is not displaying on UIView
Solution 1
If you set maskToBounds
to false
, it should show the shadow.
firstView.layer.masksToBounds = false
If the masksToBounds
property is true
, then anything that is outside the boundaries of the view will be clipped to those boundaries.
Solution 2
If you have two views view1
and view2
and view2
is just below view1
it might be that view2
covers shadow of view1
. This happens when view2
is added as subview after view1
.
Add view1
as subview after adding view2
or call [superview bringSubviewToFront:view1]
at some point.
Solution 3
Swift 4.2
extension UIView {
public func addShadowToView(shadow_color: UIColor,offset: CGSize,shadow_radius: CGFloat,shadow_opacity: Float,corner_radius: CGFloat) {
self.layer.shadowColor = shadow_color.cgColor
self.layer.shadowOpacity = shadow_opacity
self.layer.shadowOffset = offset
self.layer.shadowRadius = shadow_radius
self.layer.cornerRadius = corner_radius
}
}
Call that function as:
firstView.addShadowToView(shadow_color: UIColor.black, offset: CGSize(width: 0, height: 5), shadow_radius: 5.0, shadow_opacity: 0.5, corner_radius: 0.0)
Also make sure that your:
view
clipsToBounds
property is falsefirstView.clipsToBounds = false
firstView
backgroundColor
should not be clear colorfirstView.backgroundColor = UIColor.white
Admin
Updated on July 26, 2022Comments
-
Admin almost 2 years
I have one ViewController and in that controller there are two UIViews.
I want to add at the bottom of first UIView shadow which is shown on this second UIView.
first UIView ------------- <- shadow here secondUIView
But when I simply add this code it's not working.
firstView.layer.masksToBounds = true firstView.layer.shadowOffset = CGSizeMake(0,5) firstView.layer.shadowOpacity = 0.5 firstView.layer.shadowPath = UIBezierPath(rect: firstView.bounds).CGPath
-
euvs over 8 years@ThirdMartian Well... I don't know... Could be something else then... I run your code exactly as you posted. I only changed
true
tofalse
and made shadow offsetCGSizeMake(0, 25)
so I could clearly see the shadow. It worked. -
Admin over 8 yearsI had to change order in storyboard, anyways, thank you for help !
-
Xiao.Li over 8 yearsdon't forget adding
shadowRadius
andshadowColor
-
Matt Robinson over 6 yearsSuch a simple problem and so obvious once I read this. Thanks.
-
B L over 6 years@ThirdMartian this is most likely too late, but for those in the future,
firstView.clipsToBounds = false
would be necessary as well, just in case that was set totrue
earlier.