How to undo transparent navigation bar in iOS 11?

Viewed 187

I'm trying to create a transparent navigationBar in iOS 11.

I'm putting the following code in the VC, which works, but it stays transparent when another VC is pushed on top.

(I thought setting backgroundImage to nil again would work, but it doesn't.)

How do I get a white background when a new VC is pushed?

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.navigationBar.prefersLargeTitles = false
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    self.navigationController?.navigationBar.prefersLargeTitles = true
    self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
    self.navigationController?.navigationBar.shadowImage = nil
}
1 Answers

You could add extension to simplify interaction with UINavigationBar

extension UINavigationBar {

    func makeTransparent() {
        self.setBackgroundImage(UIImage(), for: .default)
        self.shadowImage = UIImage()
        self.isTranslucent = true
    }

    func undoTransparency() {
        self.setBackgroundImage(nil, for: .default)
    }

    func makeLargeAndTransparent() {
        makeTransparent()

        self.prefersLargeTitles = true
        self.backgroundColor = .clear
        self.barTintColor = *barTintColor*
        self.tintColor = *tintColor*
        self.largeTitleTextAttributes = [
             .font: *font.of(size: 34)*,
             .foregroundColor: *foregroundColor*
        ]

        self.titleTextAttributes = [
             .font: *font.of(size: 17)*,
             .foregroundColor: *foregroundColor*
        ]
    }

    func makeDefault() {
        undoTransparency()

        self.prefersLargeTitles = false

        self.barTintColor = *barTintColor*
        self.tintColor = *tintColor*
        self.titleTextAttributes = [
            .font: *font.of(size: 17)*,
            .foregroundColor: *foregroundColor*
        ]
    }
}
Related