我正在尝试在我的应用程序中实现颜色主题选择器。我试图克服的最后一个障碍是动态更改 UINavigationBar 的颜色。目前,我的更改颜色的功能确实有效,但只有当应用程序从关闭状态重新启动时才会生效。
我的根视图控制器设置 UINavigationBar 的初始状态,如下所示:
struct MyRootView: View {
init() {
UINavigationBar.appearance().backgroundColor = getPreferredThemeColour()
UINavigationBar.appearance().largeTitleTextAttributes = [
.foregroundColor: UIColor.white]
}
var body: some View {
...
Run Code Online (Sandbox Code Playgroud)
getPreferredThemeColour() 只是从 UserDefaults 返回所需的 UIColour
我的主题选择器具有可以更改颜色属性的按钮,如下所示:
Button(action: {
UserDefaults.standard.set(UIColor.blue, forKey: "theme")
UINavigationBar.appearance().backgroundColor = UIColor.blue }) {
Run Code Online (Sandbox Code Playgroud)
我似乎找不到任何方法来“即时”刷新 UINavigationBar 以反映所做的更改。该应用程序始终需要重新启动。
任何帮助将不胜感激!谢谢。
外观应用于外观本身之后创建的实例。所以解决办法就是NavigationView外观改变后重新创建。
这是一个有效的方法演示。使用 Xcode 11.4 / iOS 13.4 进行测试
struct DemoNavigationBarColor: View {
@State private var force = UUID()
init() {
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.configureWithOpaqueBackground()
navBarAppearance.backgroundColor = UIColor.systemRed
UINavigationBar.appearance().standardAppearance = navBarAppearance
}
var body: some View {
VStack {
NavigationView(){
List(1 ... 20, id: \.self) { item in
NavigationLink(destination:
Text("Details \(item)")
) {
Text("Row \(item)")
}
}
.navigationBarTitle("Title", displayMode: .inline)
}.id(force) // recreate NavigationView
Button("Be Green") {
UINavigationBar.appearance().standardAppearance.backgroundColor = UIColor.systemGreen
self.force = UUID() // << here !!
}
}
}
}
Run Code Online (Sandbox Code Playgroud)