Я пробовал этот метод, но он глобальный, что нежелательно.
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) {
}
}