How to change navigationBar background color locally

て烟熏妆下的殇ゞ 提交于 2021-02-10 18:18:12

问题


I tried this method but it is global which is undesired.

struct ExperienceView: View {  

    init() {
        UINavigationBar.appearance().barTintColor = #colorLiteral(red: 0.1764705882, green: 0.2196078431, blue: 0.3098039216, alpha: 1)
        UINavigationBar.appearance().isTranslucent = false
        UINavigationBar.appearance().shadowImage = UIImage()
        
    }
}

And I tried this method but it is not working, I don't know why. I even tried copying original code on SwiftUI update navigation bar title color, still not working.

struct ContentView: View {
    var body: some View {
        NavigationView {
            ScrollView {
                Text("Don't use .appearance()!")
            }
            .navigationBarTitle("Try it!", displayMode: .inline)
            .background(UINavigationConfiguration { nc in
                nc.navigationBar.barTintColor = .blue
                nc.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.white]
            })
        }
    .navigationViewStyle(StackNavigationViewStyle())
    }
}



struct UINavigationConfiguration: UIViewControllerRepresentable {
    var config: (UINavigationController) -> Void = {_ in }
    typealias UIViewControllerType = UINavigationController
    
    func makeUIViewController(context: Context) -> UINavigationController {
        return UINavigationController()
    }
    
    func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {
        if let nc = uiViewController.navigationController {
            self.config(nc)
        }
    }

}

回答1:


In the place you try to get navigation controller it is not injected yet. Here is fixed configurator (tested with Xcode 12.1 / iOS 14.1):

struct UINavigationConfiguration: UIViewControllerRepresentable {
    var config: (UINavigationController) -> Void = {_ in }
    
    func makeUIViewController(context: Context) -> UIViewController {
        let controller = UIViewController()
        DispatchQueue.main.async {
            if let nc = controller.navigationController {
                self.config(nc)
            }
        }
        return controller
    }
    
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
    }
}


来源:https://stackoverflow.com/questions/65404191/how-to-change-navigationbar-background-color-locally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!