【UIKit】Implementing TabBar and NavigationBar in Swift with Code Only

Simple Apps

NavigationBar

This post serves as a quick reference for implementing a NavigationBar in Swift using UIKit and code only. (As of January 26, 2023)

What is a NavigationBar?

A NavigationBar is the top section of the screen where the title and buttons for navigating between pages are displayed. The NavigationController manages view controllers and handles navigation between screens.

Implementation

Final Result

Here’s a simple example where I’ve just set a title for the NavigationBar:

Removing Storyboard Settings

If you’re using a project that was originally created with a Storyboard, you’ll need to remove those settings. You can find a detailed guide on how to do that in this post: Removing Storyboard Settings.

AppDelegate Configuration (iOS 15 and later)

Starting from iOS 15, the borders between the NavigationBar and TabBar are transparent by default. To restore the previous appearance (as in iOS 14 and earlier), you can add the following configuration in the application(_:didFinishLaunchingWithOptions:) method:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Configuration to display the NavigationBar as it was before iOS 15
    if #available(iOS 15.0, *) {
        // Declare the appearance for the NavigationBar
        let navigationBarAppearance = UINavigationBarAppearance()
        // Set the default background color
        navigationBarAppearance.configureWithDefaultBackground()
        
        // Assign appearance for different modes
        UINavigationBar.appearance().standardAppearance = navigationBarAppearance
        UINavigationBar.appearance().compactAppearance = navigationBarAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = navigationBarAppearance
        
        // Set the title text color
        navigationBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.black]
    }
    return true
}

ViewController Implementation

In this example, we are simply setting the title for the NavigationBar:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        self.title = "navTest"
    }
}

SceneDelegate

If you’re working with a project without a Storyboard, follow the implementation steps outlined in the “Removing Storyboard Settings” article. However, for this example, make sure to modify the highlighted section for the NavigationBar setup:

Final Thoughts

This is a very simple and straightforward implementation, but I hope it can be helpful to someone. See you in the next post!

Comments

Copied title and URL