如何在本地更改导航栏背景颜色

时间:2020-12-22 06:35:18

标签: swiftui navigation

我尝试过这种方法,但它是全局的,这是不受欢迎的。

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()
        
    }
}

我试过这个方法但它不起作用,我不知道为什么。我什至尝试复制 SwiftUI update navigation bar title color 上的原始代码,但仍然无效。

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 个答案:

答案 0 :(得分:1)

在您尝试获取导航控制器的地方,它还没有注入。这是固定配置器(使用 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) {
    }
}
相关问题