iosiphoneuinavigationbarswift5rightbarbuttonitem

Added custom shadow to navigationBar not removing


I have added the custom shadow layer to navigationBar but not able to remove now. Please guide. Below is the code to add:

let offset: CGFloat = (self.navigationController?.view.safeAreaInsets.top ?? 20)

shadowView = UIView(frame: CGRect(x: 0, y: -offset,
                                      width: (self.navigationController?.navigationBar.bounds.width)!,
                                      height: (self.navigationController?.navigationBar.bounds.height)! + offset))
shadowView?.backgroundColor = UIColor.white
self.navigationController?.navigationBar.insertSubview(shadowView!, at: 1)

let shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: shadowView!.bounds, byRoundingCorners: [.bottomLeft, .bottomRight, .topLeft], cornerRadii: CGSize(width: 0, height: 0)).cgPath

shadowLayer.fillColor = UIColor.white.cgColor

shadowLayer.shadowColor = UIColor.darkGray.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = CGSize(width: 2.0, height: 2.0)
shadowLayer.shadowOpacity = 0.8
shadowLayer.shadowRadius = 2

shadowView?.layer.insertSublayer(shadowLayer, at: 0)

For removing i have tried:

//   self.navigationController?.view.layer.shadowColor = UIColor.clear.cgColor
 //   self.navigationController?.view.layer.shadowOpacity = 0.0
   // self.navigationController?.navigationBar.isTranslucent = true
  //        for view in navigationController?.navigationBar.subviews ?? [] {
 //            if view.tag != 0 {
 //                view.removeFromSuperview()
 //            }
 //        }

self.navigationController?.navigationBar.isHidden = true
   // self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
   // self.navigationController?.navigationBar.shadowImage = UIImage()

self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear

All above statements tried but no success. Please guide for the same. Thanks


Solution

  • shadowView.removeFromSuperview()

    will do the trick.

    Are you adding and removing from different files?

    You can use:

    shadowView.tag = 1001 navigationController?.navigationBar.subviews.first(where: {$0.tag == 1001})?.removeFromSuperview()