Change the navigation bar title color in SwiftUI
In this tutorial, we will see how to change the navigation bar title color in SwiftUI.
We can customize the appearance of a navigation bar, including the navigation bar title color in various methods.
Here we will change the navigation bar title color using two different methods, those are:
- Using
UINavigationBar.appearance()
method - Using the
toolbar
modifier withToolbarItem
.
Now, let’s explore the methods one by one to achieve the task.
Using UINavigationBar.appearance() method
We can use the UINavigationBar.appearance()
method to control the appearance of the entire navigation bar, including the title text color.
It is a global setting that affects all navigation bars in the program.
Example
import SwiftUI struct ContentView: View { init() { // Set the large title text color for the entire app UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.red] } var body: some View { NavigationView { Text("Content goes here") .navigationBarTitle("Title") } } }
In the above program, the UINavigationBar.appearance()
is used to access the appearance proxy for the navigation bar.
I have set the largeTitleTextAttributes
to make the font size of the Navigation bar title larger.
Then, I have used the .foregroundColor
modifier to define the color of the Navigation bar title text.
Output:
Using the toolbar modifier with ToolbarItem
We can also customize the appearance of a navigation bar title using the toolbar
modifier along with ToolbarItem
.
First of all, we have to apply the toolbar
modifier to the NavigationView
, and within the toolbar
modifier, we have to use the ToolbarItem
to add items to the navigation bar.
Now, within this ToolbarItem
we can create a Text view that will be the title of the Navigation bar and then we can use the foregroundColor()
modifier on that text view to change the title color.
Example
import SwiftUI struct ContentView: View { var body: some View { NavigationView { Text("Content goes here") .toolbar { // Toolbar item placement for navigation bar ToolbarItem(placement: .navigation) { // Text view serving as the title Text("Title") .font(.largeTitle) // Set the font size to large .foregroundColor(.red) // Set the text color to red } } } } }
In the above program, I have used the .font(.largeTitle)
modifier on the Text
view to change the font size to large.
Then, I have applied the foregroundColor()
modifier on the Text
view and specified the color .red
to change the title color to red.
Output:
Leave a Reply