Shadow is not displaying on UIView

16,947

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 false

    firstView.clipsToBounds = false
    
  • firstView backgroundColor should not be clear color

    firstView.backgroundColor = UIColor.white
    
Share:
16,947
Admin
Author by

Admin

Updated on July 26, 2022

Comments

  • Admin
    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
    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 to false and made shadow offset CGSizeMake(0, 25) so I could clearly see the shadow. It worked.
  • Admin
    Admin over 8 years
    I had to change order in storyboard, anyways, thank you for help !
  • Xiao.Li
    Xiao.Li over 8 years
    don't forget adding shadowRadius and shadowColor
  • Matt Robinson
    Matt Robinson over 6 years
    Such a simple problem and so obvious once I read this. Thanks.
  • B L
    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 to true earlier.