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

 In this tutorial, we are going to learn about how to add shadow to UIView in swift. Giving shadow to our view controls increase the visibility of app’s user interface because it adds hover effect, so giving user a nice feel of the app. Please follow the below steps that will create shadow on all sides of UIView.
 

Steps to add shadow to 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 to give transparency to our view. Default value is 0.0 (complete transparent). You can set the value in range of 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:

 

Where to go from here

In this post, we learned how to add shadow to UIView in swift. We looked over some properties of CALayer so that we can make use of them in achieving the shadow effect.