12 Feb 2018

Add shadow to all sides of UIView in swift 4

Add shadow to all sides of UIView in swift 4

Add shadow to all sides of UIView in swift 4

 In this tutorial, we are going to learn about adding shadow to view (UIView) in swift/ swift 4. Giving shadow to our view controls increase the visibility of app's user interface. Follow the below steps that will create shadow on all sides of UIView. 

Step 1: shadowColor: this property of CALayer, allows us to give type of color to our shadow we want to give to an UIView.

            self.cntView.layer.shadowColor = UIColor.lightGray.cgColor

Note: replace cntView, with your view object.

Step 2: shadowOpacity: this property allows us too give transparency to our view. Default value is 0.0 (complete transparent). You can set the value between 0.0 to 1.0

            self.cntView.layer.shadowOpacity = 0.5

Step3: shadowRadius: this property allows us to give radius to the shadow    

           self.cntView.layer.shadowRadius = 10.0

Step 4:shadowOffsett: offset for layer's shadow. Default is (0.0, -3.0). Default To give shadow to all sides of view, we will set this to .zero

            self.cntView.layer.shadowOffset = .zero

Step 5 : shadowPath: shape of the shadow. Default is nil, we will use UIBezierPath to set path for our shadow.
            self.cntView.layer.shadowPath = UIBezierPath(rect: self.cntView.bounds).cgPath
            self.cntView.layer.shouldRasterize = true

Complete Code:

Video tutorial to add shadow to all sides of UIView:

No comments:

Post a Comment