I could successfully remove the shadow below the navigation bar with the following line of code.
self.navigationController?.navigationBar.shadowImage = UIImage()
When I added a search controller however, the shadow reappeared.
self.navigationItem.searchController = UISearchController(searchResultsController: nil)
I tried the following, but resulted an unexpected behavior.
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.barTintColor = .white
self.navigationController?.navigationBar.isTranslucent = false
How do I remove the shadow under a navigation bar when there is a search controller attached?
I have not found good solution too...
for now I will hide it this way:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let imageView = navigationItem.searchController?.searchBar.superview?.subviews.first?.subviews.first as? UIImageView {
imageView.isHidden = true
}
}
Here's the solution that I use
Create a separate class extending a UINavigationController
instance, lets call it BaseNavigationController
. Here's your class for you
If you are using storyboards, assign BaseNavigationController
to your UINavigationController scene in the storyboard
UINavigationController.init(rootViewController: someViewControllerInstance)
then simply use BaseNavigationController.init(rootViewController: someViewControllerInstance)
An example of the class is shown below:
open class BaseNavigationController:UINavigationController {
override open func viewDidLoad() {
super.viewDidLoad()
setNavigationBar()
setNavBarBorder(false)
}
func setNavigationBar(color:UIColor?=UIColor.white, tint:UIColor?=UIColor.darkGray){
let appearance = UIBarButtonItem.appearance()
appearance.setBackButtonTitlePositionAdjustment(UIOffset.init(horizontal: 0.0, vertical: 0), for: .default)
self.navigationBar.barTintColor = color!
self.navigationBar.isTranslucent = false
self.navigationBar.tintColor = tint!
self.navigationBar.titleTextAttributes = [ NSAttributedString.Key.foregroundColor: tint! ]
}
func setTitleColor(_ color:UIColor?=UIColor.darkGray){
}
func setNavBarBorder(_ enable:Bool) {
self.navigationBar.setBackgroundImage((enable ? nil : UIImage()), for: UIBarMetrics.default)
self.navigationBar.shadowImage = (enable ? nil : UIImage())
self.navigationBar.setValue(true, forKey: "hidesShadow")
}
}
Now, the fun part, if you are handling ambiguous layout you might need to do this in viewWillLayoutSubviews
otherwise putting this bit of code in viewWillAppear
of the viewController instance.
(self.navigationController as? BaseNavigationController)?. setNavBarBorder(false)
the interesting bit of code is in self.navigationBar.setValue(true, forKey: "hidesShadow")
, for some versions of iOS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With