I'm developing a simple application and one of the settings lets the user select an application theme. By selecting one of them every icon and navigation back button's foreground color changes to that color dynamically, using an environment object.
This is the settings View with the different options and the currently selected theme is the default one, hence why the navigation title is already red.
Settings View:
This is the theme selection View. You can see that the currently selected theme is the red one.
Theme selection View:
I've tried different solutions and every single one of them works but only when the application starts, meaning that when I change the theme, the icons and the navigation back buttons change, except the navigation bar title obviously. The solution I'm currently using is writing this in the main swift file:
import SwiftUI
@main
struct Application: App {
...
}
extension View {
@available(iOS 14, *)
func navigationBarTitleTextColor(_ color: Color) -> some View {
let uiColor = UIColor(color)
// Set appearance for both normal and large sizes.
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: uiColor ]
UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: uiColor ]
return self
}
}
and writing .navigationBarTitleTextColor(Color(selectedTheme.assetName()))
after the list in the NavigationStack in the Settings View file.
I found it in another Stack Overflow question answer by Yoon Lee and cliss, the problem is again the fact that even by using the environment object it remains static to the color set by default (red in my case).
Other solutions I've tried are the following:
- by Becky Hansmeyer
- by Eric Callanan
As you can see, I tried changing the theme of the app to blue and the tick on the right of the list item and the navigation back button changed to that color, except for the navigation bar title which remained the default color red, set as default in the Theme class I've created.
Situation after changing theme:
DISCLAIMER: I'm pretty new to Swift, SwiftUI or the whole iOS development pipeline so please be kind and clear in the answers, thank you.