Search code examples
iosswiftstoryboard

How to add view on top of navigation bar


How to add view above navigation bar? I have a custom navigation controller and I want to present a view above nav bar (like on the screen), so it should be visible on other ViewControllers

Would be great if the solution will be on storyboard. Like that

Tried to add on UIWindow did't help.


Solution

  • Swift 4.2, Xcode 10+

    Okay, from what I can tell (via your comment reply, though it still isn't 100% clear), the best solution to your question would be to make the navigation bar transparent, such that you can see any navigationController-presented view controllers underneath it. For this, I'd suggest the following extension to UIViewController:

    extension UIViewController {    
        func setupTransparentNavigationBarWithBlackText() {
            setupTransparentNavigationBar()
            //Status bar text and back(item) tint to black
            self.navigationController?.navigationBar.barStyle = .default
            self.navigationController?.navigationBar.tintColor = .black
        }
    
        func setupTransparentNavigationBarWithWhiteText() {
            setupTransparentNavigationBar()
            //Status bar text and back(item) tint to white
            self.navigationController?.navigationBar.barStyle = .blackTranslucent
            self.navigationController?.navigationBar.tintColor = .white
        }
    
        func setupTransparentNavigationBar() {
            self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
            self.navigationController?.navigationBar.shadowImage = UIImage()
            self.navigationController?.navigationBar.backgroundColor = .clear
            self.navigationController?.navigationBar.isTranslucent = true
        }
    }
    

    Using either of the first two methods in viewWillAppear of your UIViewController subclasses will let you make the navigation bar completely transparent with the statusBar text + wifi/battery indicators black or white as desired. From this, you can then display anything under the navigation bar by pinning your constraints to view.bounds.topAnchor. E.g. for a transparent navigation controller with white statusBar text:

    class YourViewController: UIViewController {
        override func viewWillAppear(_ animated: Bool) {
            setupTransparentNavigationBarWithWhiteText()
        }
    }