UINavigationBar in UIKit

UINavigationBar is an essential component in the UIKit framework, providing a navigation interface that is commonly used to navigate through hierarchical content in iOS applications.

article

UINavigationBar in UIKit

UINavigationBar is an essential component in the UIKit framework, providing a navigation interface that is commonly used to navigate through hierarchical content in iOS applications. In this article, we will explore what UINavigationBars are, the various functionalities they offer, and provide practical code examples to demonstrate how you can implement and customize them in your iOS projects.


What is a UINavigationBar?

A UINavigationBar is a control that provides a bar at the top of the screen, typically containing a title, left and right bar button items, and optionally a prompt. It is used in conjunction with UINavigationController to manage a stack of view controllers and provide a navigation interface that allows users to move forward and backward through different views.


UINavigationBars offer a range of functionalities and customization options. Here are some key things you can do with UINavigationBars:


  • Display Titles: Set a title for the navigation bar to indicate the current view.
  • Bar Button Items: Add buttons to the left and right sides of the navigation bar for additional actions.
  • Customize Appearance: Adjust the navigation bar's appearance, including background color, text attributes, and more.
  • Prompt: Display a small prompt message below the title.
  • Large Titles: Enable large titles for better visual hierarchy and improved accessibility.

Implementing UINavigationBar in Swift

Let's dive into some code examples to see how you can create, customize, and work with UINavigationBars in Swift.


To create a simple UINavigationBar, you typically use a UINavigationController to manage the navigation stack. Here is an example:


import UIKit

class FirstViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        title = "First View"

        // Create a button to navigate to the next view
        let nextButton = UIButton(type: .system)
        nextButton.setTitle("Next", for: .normal)
        nextButton.addTarget(self, action: #selector(navigateToNextView), for: .touchUpInside)
        nextButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(nextButton)

        // Set Auto Layout constraints for the button
        NSLayoutConstraint.activate([
            nextButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            nextButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }

    @objc func navigateToNextView() {
        let nextViewController = SecondViewController()
        navigationController?.pushViewController(nextViewController, animated: true)
    }
}

class SecondViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        title = "Second View"
    }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        let firstViewController = FirstViewController()
        let navigationController = UINavigationController(rootViewController: firstViewController)
        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()
        return true
    }
}

In this example, we create a UINavigationController and set the root view controller to an instance of FirstViewController. We also create a button in FirstViewController that navigates to SecondViewController when tapped. The navigation bar automatically displays the titles of the view controllers.


Adding Bar Button Items


You can add bar button items to the navigation bar to provide additional actions. Here is an example of adding a left and a right bar button item:


import UIKit

class FirstViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        title = "First View"

        // Create left bar button item
        let leftBarButtonItem = UIBarButtonItem(title: "Left", style: .plain, target: self, action: #selector(leftBarButtonTapped))
        navigationItem.leftBarButtonItem = leftBarButtonItem

        // Create right bar button item
        let rightBarButtonItem = UIBarButtonItem(title: "Right", style: .plain, target: self, action: #selector(rightBarButtonTapped))
        navigationItem.rightBarButtonItem = rightBarButtonItem

        // Create a button to navigate to the next view
        let nextButton = UIButton(type: .system)
        nextButton.setTitle("Next", for: .normal)
        nextButton.addTarget(self, action: #selector(navigateToNextView), for: .touchUpInside)
        nextButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(nextButton)

        // Set Auto Layout constraints for the button
        NSLayoutConstraint.activate([
            nextButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            nextButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }

    @objc func leftBarButtonTapped() {
        print("Left bar button tapped")
    }

    @objc func rightBarButtonTapped() {
        print("Right bar button tapped")
    }

    @objc func navigateToNextView() {
        let nextViewController = SecondViewController()
        navigationController?.pushViewController(nextViewController, animated: true)
    }
}

class SecondViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        title = "Second View"
    }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        let firstViewController = FirstViewController()
        let navigationController = UINavigationController(rootViewController: firstViewController)
        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()
        return true
    }
}

In this example, we add left and right bar button items to the navigation bar in FirstViewController. We set their titles and actions, which are handled by the leftBarButtonTapped and rightBarButtonTapped methods, respectively.


Customizing UINavigationBar Appearance


You can customize the appearance of the UINavigationBar to match the design of your application. Here is an example of customizing the navigation bar's background color and title text attributes:


import UIKit

class FirstViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        title = "First View"

        // Customize the navigation bar appearance
        if let navigationBar = navigationController?.navigationBar {
            navigationBar.barTintColor = .darkGray
            navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
            navigationBar.tintColor = .white
        }

        // Create a button to navigate to the next view
        let nextButton = UIButton(type: .system)
        nextButton.setTitle("Next", for: .normal)
        nextButton.addTarget(self, action: #selector(navigateToNextView), for: .touchUpInside)
        nextButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(nextButton)

        // Set Auto Layout constraints for the button
        NSLayoutConstraint.activate([
            nextButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            nextButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }

    @objc func navigateToNextView() {
        let nextViewController = SecondViewController()
        navigationController?.pushViewController(nextViewController, animated: true)
    }
}

class SecondViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        title = "Second View"
    }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        let firstViewController = FirstViewController()
        let navigationController = UINavigationController(rootViewController: firstViewController)
        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()
        return true
    }
}

In this example, we customize the UINavigationBar by setting its bar tint color, title text attributes, and tint color. This changes the background color of the navigation bar and the color of the title and bar button items.


Using Large Titles in UINavigationBar


Starting with iOS 11, you can enable large titles in UINavigationBar to improve visual hierarchy and accessibility. Here is an example of using large titles:


import UIKit

class FirstViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        title = "First View"
        navigationController?.navigationBar.prefersLargeTitles = true

        // Create a button to navigate to the next view
        let nextButton = UIButton(type: .system)
        nextButton.setTitle("Next", for: .normal)
        nextButton.addTarget(self, action: #selector(navigateToNextView), for: .touchUpInside)
        nextButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(nextButton)

        // Set Auto Layout constraints for the button
        NSLayoutConstraint.activate([
            nextButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            nextButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }

    @objc func navigateToNextView() {
        let nextViewController = SecondViewController()
        navigationController?.pushViewController(nextViewController, animated: true)
    }
}

class SecondViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        title = "Second View"
        navigationController?.navigationBar.prefersLargeTitles = true
    }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        let firstViewController = FirstViewController()
        let navigationController = UINavigationController(rootViewController: firstViewController)
        navigationController.navigationBar.prefersLargeTitles = true
        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()
        return true
    }
}

In this example, we enable large titles for the UINavigationBar by setting the prefersLargeTitles property to true. This is done both in the view controllers and the UINavigationController to ensure consistent behavior across the navigation stack.


Conclusion


UINavigationBars are essential components for providing a navigation interface in your iOS applications. In this article, we've covered the basics of what UINavigationBars are, their various functionalities, and provided practical code examples to help you implement and customize them in your own projects. From creating simple navigation bars to adding bar button items and customizing their appearance, mastering UINavigationBars is crucial for building intuitive and user-friendly navigation interfaces.


Understanding and effectively utilizing UINavigationBars can significantly enhance your app's navigation and user experience. Experiment with different UINavigationBar properties and techniques to create dynamic and engaging navigation interfaces in your iOS applications.

instructor

Exodai INSTRUCTOR!

Johan t'Sas

Owner and Swift developer!