Change the background color of the Navigation Bar in Swift UI I don't want to use ʻUI Appearance` (strong will)
--Changed BackgroundColor of NavigationBar without using ʻUINavigationBar.appearance () --ʻCreate View that you want to change the Style of NavigationBar with UIViewControllerRepresentable
--Set the above View to .background ()
of View that uses NavigationBar
import SwiftUI
import UIKit
struct NavigationConfigurator: UIViewControllerRepresentable {
var configure: (UINavigationController) -> Void = { _ in }
func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationConfigurator>) -> UIViewController {
UIViewController()
}
func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavigationConfigurator>) {
if let nc = uiViewController.navigationController {
self.configure(nc)
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
Text("Don't use .appearance()!")
.navigationBarTitle("Try it!", displayMode: .inline)
.background(NavigationConfigurator { nc in
//OK in the same way as changing the style of the NavigationBar in UIKit
nc.navigationBar.barTintColor = .blue
nc.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.white]
})
}
}
}
As of October 11, 2020 Xcode 12.0.1 Swift 5.3 I don't know because I haven't verified the environment other than this. I think it is possible in an environment where Swift UI works
For the time being, when I googled it quickly, in some articles, I wondered if it could only be done with ʻUINavigationBar.appearance ()` during the initialization process of the constructor etc.: sob:
Certainly, you can change what you can change with ʻUINavigationBar.appearance ()`, It is difficult to change the color for each screen (I mean, this is not possible, ...)
SwiftUI update navigation bar title color Someone has taught me how to change it to a nice one: smile:
The style is not reflected unless the preview is set to live mode It doesn't matter because you only have to put it in live mode
So I was able to change the background color nicely using ʻUIViewControllerRepresentable` SwiftUI is still growing, so it seems that I have to master this child
Recommended Posts