Set background image to navigationbar in Swift – iOS Swift Tutorial

In this tutorial, we will learn how to set background image to UINavigationBar a background image. Since the iOS 13.0, we do have a new property called appearance, that allows us to change color, font, and image of UINavigationController or UINavigationBar. Prior to iOS 13.0, we can do this by simply setting backgroundImage to UINavigationBar. But this, will not work in iOS 13.0 and onward. That’s what we are going to learn in this tutorial, as i faced this issue too during developing apps.

Add background image to UINavigationBar

To add background image, we need to drag an image to our project. Then we need to add code related to UINavigationBarAppearance, and i will do this by creating an extension of UINavigationController. Below is the code for the UINavigationController extension.

extension UINavigationController {
    
    func setNavigationBarAppearance() {
        self.navigationBar.tintColor = .black
        let appearance = UINavigationBarAppearance()
        appearance.configureWithOpaqueBackground()
        appearance.titleTextAttributes = [
            NSAttributedString.Key.foregroundColor: UIColor.white]
        appearance.backgroundImage = UIImage(named: "navbarbackground")
        appearance.shadowColor = .clear
        self.navigationBar.standardAppearance = appearance
        self.navigationBar.scrollEdgeAppearance = self.navigationBar.standardAppearance
    }
}

In the above code, we set foreground color of UINavigationBar title, and background image of UINavigationBar. We also set shadow color to .clear i.e. clear color, since we do not need any shadow to navigation bar. Default there is a slight black line, though you set shadowImage and shadow color separately to UINavigationBar. Lastly set UINavigationController appearance to the one we created, and call setNavigationBarAppearance function in your AppDelegate class or any other class. That’s it and you solved your problem of adding background image to UINavigationBar. If you want to change font of UINavigationBar, textcolor or title font size you can do it here by setting properties of UINavigationBarAppearance.