Search code examples
swiftxcodeuinavigationcontrolleruibackgroundcolor

Navigation Controller. Background color


For one controller I have settings:

self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()

and

override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        var offset = scrollView.contentOffset.y / 150
        if offset > 1 {
            offset = 1
            self.navigationController?.navigationBar.backgroundColor = UIColor(red: 82/255, green: 76/255, blue: 70/255, alpha: offset)
            UIApplication.shared.statusBarView?.backgroundColor = UIColor(red: 82/255, green: 76/255, blue: 70/255, alpha: offset)
            self.navigationItem.title = name
        } else {
            self.navigationController?.navigationBar.backgroundColor = UIColor(red: 82/255, green: 76/255, blue: 70/255, alpha: offset)
             UIApplication.shared.statusBarView?.backgroundColor = UIColor(red: 82/255, green: 76/255, blue: 70/255, alpha: offset)
            self.navigationItem.title = ""
        }
    }

The main problem is that when i press back button, settings save. In the end i have white NavigationController. How can I make the settings not taken from the last controller?

func makeSearchController() {
        searchController = UISearchController(searchResultsController: nil)
        navigationItem.searchController = searchController
        navigationItem.hidesSearchBarWhenScrolling = false
        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.tintColor = .white
        searchController.searchBar.placeholder = "Блюдо или продукт ..."
    }

Solution

  • You can reset the navigation controller's color in viewWillDisappear, like this:

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.backgroundColor = UIColor(red: 221/255, green: 221/255, blue: 225/255, alpha: offset) //gray color
        UIApplication.shared.statusBarView?.backgroundColor = UIColor(red: 221/255, green: 221/255, blue: 225/255, alpha: offset) //gray color
    }