How to Create a Gradient NavBar in Swift 5 and iOS 13
Give your navigation bar a better design
I remember when I first saw the Photos App in iOS 13, what stood out for me was the gradient navigation bar. Very simple, yet very elegant. I decided to recreate it and share how I recreated it.
Side note: Everything is done programmatically.
New Project and Setting Up the UINavigationController
Lets first create a new project as a single-view app.
We will first start in the
SceneDelegate.swift file to set up the
UINavigationController to programmatically set the
rootViewController to be the
ViewController wrapped in the
willConnectTo scene function, we will set up the
If you build and run the file, you should have the
Variables Needed and Setting Up the UICollectionView
Side note: Although the
UICollectionView is not necessary for creating the gradient
NavBar, I will quickly create one just to demonstrate that the gradient will work as it should, later in this tutorial.
Here are the variables needed for the gradient
Side note: Skip this segment if you don’t need to create a
Here are the variables and delegates needed for
As soon as you try to build that, you will have Swift compiler errors because you will need to conform to the protocols from the
But, as we add the necessary protocols, we will add the other
UICollectionView functions as an extension of the
As soon as you run this, you will notice that the
UICollectionView is not appearing. That is because we need to anchor it. We can create a function
setupCollectionView and call it in the
If you run and build the code, you should now have this:
The next step is to make a clear
navBar. We will start this by creating an extension of the
Let’s create a new file and name it
UIViewControllerExtensions and add a function that will allow us to create a clear
Side note: When we create the extension, it allows us to call this function in any class of this project rather than coding out the same function, reducing redundancy.
Since we are in this file, let’s also create a function,
setupGradient, that will return a gradient. We will need this for later.
Clear NavBar and Gradient
ViewController class, in the
ViewDidLoad function, we can call the
setupClearNavBar function we created in the
To verify that
NavBar is clear and hasn’t disappeared, we can add a title to the
NavBar in the
navigationItem.title = “A NavBar”
Let’s now add the gradient. All we are doing to create the gradient is anchor the
gradientView underneath the
navBar. We can create the
setupGradient function in the
ViewController class and call it in the
Ensure you are calling the functions in the
viewDidLoad function as follows:
Once you do all that and run the app, it should look like this:
Link to the GitHub Repo.
Thanks for reading!