提问者:小点点

SwiftUI-动态刷新UINavigationBar.appeance()。BackgroundColor


我正在尝试在我的应用程序中实现一个颜色主题选择器。 我试图克服的最后一个障碍是动态改变我的UinavigationBar的颜色。 目前,我改变颜色的功能确实起作用,但只有当应用程序已经从关闭状态重新启动时才会生效。

我的根视图控制器按如下方式设置UINavigationBar的初始状态:

struct MyRootView: View {

            init() {
                UINavigationBar.appearance().backgroundColor = getPreferredThemeColour() 
                UINavigationBar.appearance().largeTitleTextAttributes = [
                    .foregroundColor: UIColor.white]
            }

var body: some View {
...

getPreferredThemeColour()只是从UserDefaults返回所需的UIColour

我的主题选择器有一些按钮可以改变颜色属性,如下所示:

 Button(action: {
 UserDefaults.standard.set(UIColor.blue, forKey: "theme")
 UINavigationBar.appearance().backgroundColor = UIColor.blue }) {

我似乎找不到任何方法来“即时”刷新UINavigationBar以反映所做的更改。 应用程序总是需要重新启动。

如有任何帮助,我们将不胜感激!!!! 谢谢。


共1个答案

匿名用户

应用于在外观本身之后创建的实例的外观。 因此解决方案是在外观更改后重新创建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 !!
            }
        }
    }
}