问题
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