I\'m trying to create a button with rounded corners and a drop shadow. No matter how I switch up, the button will not display correctly. I\
Using CAShapeLayer and UIBezierPath we can easily add shadow and corner radius to UIView and the class derived from it like UIButton, UIImageView, UILabel etc.
We will add UIView Extension and the good point of this is, you only need to write just one line of code to achieve this.
You can round specific corner as well Just add below UIView Extension in your project:
extension UIView {
func addShadow(shadowColor: UIColor, offSet: CGSize, opacity: Float, shadowRadius:
CGFloat, cornerRadius: CGFloat, corners: UIRectCorner, fillColor: UIColor = .white) {
let shadowLayer = CAShapeLayer()
let size = CGSize(width: cornerRadius, height: cornerRadius)
let cgPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: size).cgPath //1
shadowLayer.path = cgPath //2
shadowLayer.fillColor = fillColor.cgColor //3
shadowLayer.shadowColor = shadowColor.cgColor //4
shadowLayer.shadowPath = cgPath
shadowLayer.shadowOffset = offSet //5
shadowLayer.shadowOpacity = opacity
shadowLayer.shadowRadius = shadowRadius
self.layer.addSublayer(shadowLayer)
}
}
Now just write below code to add shadow and corner radius
self.myView.addShadow(shadowColor: .black, offSet: CGSize(width: 2.6, height: 2.6),
opacity: 0.8, shadowRadius: 5.0, cornerRadius: 20.0, corners: [.topRight, .topLeft],
fillColor: .red)