Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transparent navigation bar glitch

I need to make the navigation bar in some view controllers transparent (but with the bar buttons visible).

I wrote the following extension for that.

extension UINavigationBar {
    func setTransparent(_ flag: Bool) {
        if flag == true {
            setBackgroundImage(UIImage(), for: .default)
            shadowImage = UIImage()
            backgroundColor = .clear
            isTranslucent = true
        } else {
            setBackgroundImage(nil, for: .default)
        }
    }
}

The default styles for my navigation bars are as follows.

UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().barTintColor = UIColor(red: 45/255, green: 93/255, blue: 131/255, alpha: 1)
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]

All this works fine. But there's a problem if I have to turn off the transparent effect.

Say in the first view controller I don't need the navigation bar to be transparent.

class FirstViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.navigationBar.setTransparent(false)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.isTranslucent = false
    }
}

I push to the second view controller from here. In here, the navigation bar is transparent.

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.navigationBar.setTransparent(true)
    }

}

Now when I pop back to the previous view controller, I have to explicitly set the isTranslucent property to false. I do that in the viewWillAppear as you can see in the first code snippet.

But the problem is, the navigation bar is black for a second when it happens.

enter image description here

I want this to be smooth. How do I avoid this?

Demo project uploaded here.


I tried the solution described here to a similar question. But it doesn't completely fix my issue. The black bar is gone but the navigation bar doesn't appear for a second just like before as you can see here.

like image 439
Isuru Avatar asked Apr 05 '18 06:04

Isuru


1 Answers

Black navigation bar you see is actually a navigation controller view background color. Try add this code in first view controller viewDidLoad method

navigationController?.view.backgroundColor = navigationController?.navigationBar.barTintColor
like image 186
Dmytro Trofymenko Avatar answered Sep 17 '22 23:09

Dmytro Trofymenko