Give Shadow And Corner Radius To Same View In iOS

Posted By : Vasu Saini | 17-Nov-2017

Here today we will know about some tricky way to give shadow to view with corner radius , it is not possible by default in iOS to make a view with both specifications i.e a view having rounded corners as well shadow of view.

Lets take a look to view shown below , android have card view by default , but in iOS there is not such type of view available we have to make it by giving shadow to view, but when it comes to give rounded corners to a view having shadow it is not a easy task as it seems to be.

 

Business benefits of Bitcoin

Step 1. When  we have  to give just shadow to a view we can use code shown below:-

extension UIView {

func shadow(color: UIColor = UIColor.darkGray) {
    self.layer.shadowColor = color.cgColor;
    self.layer.shadowOpacity = 0.5
    self.layer.shadowRadius = 1
    self.layer.masksToBounds = false
    self.layer.shadowOffset = CGSize(width: 1.5, height: 1.5)
    }

}

It will show shadow of any component having UIView as superclass of if in any hirarchy.
If you read code there is propery masksToBounds and is set to be false when it comes to give shadow to a view. 

Step 2. But if someone say give corner radius to same view then we have to write code as given below:-

extension UIView {
func setRoundCorner(){
                self.layer.cornerRadius = self.layer.frame.size.height/2
                self.layer.masksToBounds = true
    }
}

Here again same property masksToBounds is set to be true to set corners round

Step 3. This is main problem we faces during performing such task module.

Step 4. Let us know how to do such task, there is class UIBezierPath in UIKit framework which is used to draw views and cut view with custom paths.

Step 5. We will make a Bezierpath have frame same to view on which shadow is required.

Step 6. Now the view's layer have a propery shadowpath which accepts cgPath.

Step 7. We type cast made that bezirePath to cgPath and the set it to shadowPath.

Step 8 As we manually defined the shadowPath of view there is no need to set masksToBounds to true.

Step 9. Code is appears something like given below.
 

 

 

   

extension UIView {

 func setShadowWithCornerRadius(corners : CGFloat){

        self.layer.cornerRadius = corners

        let shadowPath2 = UIBezierPath(rect: self.bounds)

        self.layer.masksToBounds = false

        self.layer.shadowColor = UIColor.lightGray.cgColor

        self.layer.shadowOffset = CGSize(width: CGFloat(1.0), height: CGFloat(3.0))

        self.layer.shadowOpacity = 0.5

        self.layer.shadowPath = shadowPath2.cgPath

 

        }

    }

 

Step 10. All done

 

 

 

 

 

 

 

Request for Proposal

Recaptcha is required.

Sending message..