iOS can dynamically generate shadows for any UIView

shadow1

  • shadowColor is the color of the shadow & need to be a CGColor.
  • shadowRadius is the width of the shadow along the shadow path.
  • shadowOpacity determines the opacity of the shadow.
  • shadowOffset is a CGSize representing how far to offset the shadow from the path.
  • //MARK:- ShadowView
    extension UIView {
    //Shadow view
    func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
    self.layer.masksToBounds = false
    self.layer.shadowColor = color.cgColor
    self.layer.shadowOpacity = opacity
    self.layer.shadowOffset = offSet
    self.layer.shadowRadius = radius
    self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
    self.layer.shouldRasterize = true
    self.layer.rasterizationScale = scale ? UIScreen.main.scale : 1
    }
    }

    You can use inside viewDidLayoutSubviews, its due to update constraints properly for shadow view.

    //MARK:- viewDidLayoutSubviews
    override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.yourView.dropShadow(color: .black, opacity: 1, offSet: CGSize(width: -1, height: 1), radius: 3, scale: true)
    }