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



我尝试过这个方法,但它是全局的,这是不需要的。

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上更新导航栏标题颜色的原始代码,但仍然不起作用。

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测试(:

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

最新更新