3

I am trying to make my Navigation bar transparent. It works when i create the function within the same ViewController however i want to reuse it in many other ViewControllers so i decided to use an extension extending the UINavigationController. When i try calling the function into ViewDidLoad, it doesn't work.

import UIKit

class StudentsViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.makeNavigationBarTransparent()   
    } 
}

Here is my extension

import UIKit

extension UINavigationController {
    func makeNavigationBarTransparent() {
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
    }
}
sk123
  • 580
  • 1
  • 8
  • 29

3 Answers3

3

Since you decided to write the extension for navigation controller, you must write it from its prespective:

import UIKit

extension UINavigationController {
    func makeNavigationBarTransparent() {
        self.navigationBar.setBackgroundImage(UIImage(), for: .default)
        self.navigationBar.shadowImage = UIImage()
    }
}
Štěpán
  • 328
  • 3
  • 12
3

You don't need the on the navigationController?.

extension UINavigationController {
    func makeNavigationBarTransparent() {
        navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationBar.shadowImage = UIImage()
    }
}
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
1

It's because your viewController isn't placed in your navigation stack yet. If your vc isn't placed in navigation stack then self.navigationController will returns nil.

Try to move your makeNavigationBarTransparent() call to viewWillAppear method.

U. Benlice
  • 901
  • 9
  • 14