To update the navigation bar title color in SwiftUI, you can use the navigationBarTitle
modifier along with the foregroundColor
modifier to adjust the color. Here’s an example:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
Text("Hello, World!")
.navigationBarTitle("Title", displayMode: .inline)
.navigationBarItems(trailing: Button(action: {}) {
Image(systemName: "gear")
})
.foregroundColor(.blue) // Change navigation bar title color
}
}
}
In the above example, .foregroundColor(.blue)
is used to change the color of the navigation bar title to blue. You can replace .blue
with any color you prefer.
In SwiftUI, customizing the navigation bar title color can be a bit tricky, but there are workarounds. Let’s explore a couple of approaches:
-
Using
UINavigationBar.appearance()
(Global Change): You can set the text color for the navigation bar title globally usingUINavigationBar.appearance()
. This approach affects all navigation bars in your app. Here’s an example:
import SwiftUI
struct ContentView: View {
init() {
// Set the title color globally
UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.red]
}
var body: some View {
NavigationView {
ScrollView {
Text("Don't use .appearance()!")
}
.navigationBarTitle("Try it!", displayMode: .inline)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
Using UIViewControllerRepresentable
(Per-View Customization): If you want to customize the title color for a specific view, you can create a UIViewControllerRepresentable
that modifies the navigation bar appearance. Here’s an example:
import SwiftUI
struct NavigationConfigurator: UIViewControllerRepresentable {
var configure: (UINavigationController) -> Void = { _ in }
func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationConfigurator>) -> UIViewController {
UIViewController()
}
func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavigationConfigurator>) {
if let nc = uiViewController.navigationController {
// Customize the navigation bar appearance
nc.navigationBar.barTintColor = .blue
nc.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
ScrollView {
Text("Customize the navigation bar appearance")
}
.navigationBarTitle("Custom Title")
.background(NavigationConfigurator { nc in
// Customize the navigation bar for this view
nc.navigationBar.barTintColor = .blue
nc.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
})
}
.navigationViewStyle(StackNavigationViewStyle())
}
}