Search code examples
iosswiftuinavigationcontrolleruinavigationbarios-extensions

How to call a function from an extension to UIViewController in Swift


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()
    }
}

Solution

  • You don't need the on the navigationController?.

    extension UINavigationController {
        func makeNavigationBarTransparent() {
            navigationBar.setBackgroundImage(UIImage(), for: .default)
            navigationBar.shadowImage = UIImage()
        }
    }