如何在本地更改导航栏背景颜色 [英] How to change navigationBar background color locally

查看:84
本文介绍了如何在本地更改导航栏背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我试过这个方法但它不起作用,我不知道为什么.我什至尝试在 SwiftUI 更新导航栏标题颜色上复制原始代码,但仍然没有工作.

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

}

推荐答案

在您尝试获取导航控制器的地方,它还没有注入.这是固定配置器(使用 Xcode 12.1/iOS 14.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) {
    }
}

这篇关于如何在本地更改导航栏背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆