【问题标题】:How to change navigationBar background color locally如何在本地更改导航栏背景颜色
【发布时间】:2020-12-22 06:35:18
【问题描述】:

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

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

}

【问题讨论】:

    标签: swiftui navigation


    【解决方案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) {
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-27
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多