I am currently struggling with defining multiple custom UINavigationBars for different Views in SwiftUI.
I have defined two different appearances in my UINavigationBar extension: a default one and one with a transparent background.
I am calling UINavigationBar.defaultNavigationBar()
in my entry ContentView().
And when I'm navigating to another view via NavigationLink { ... }
, I want to apply the different navigation bar appearances based on the logic in setNavigationBarStyle
The switch does not work and the UINavigationBar keeps its initial configuration which is defined in defaultNavigationBar()
So my question is, is this the right approach and I am missing some configurations? If not, what is the right approach to style the UINavigationBar differently based on my current view?
import SwiftUI
extension UINavigationBar {
static let appearance = UINavigationBarAppearance()
static func defaultNavigationBar() {
appearance.backgroundColor = UIColor(Color.audi.barBackground)
appearance.titleTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor(Color.audi.barContent),
NSAttributedString.Key.font: UIFont(name: Fonts.typeVFNormalBold.rawValue, size: 12)!
]
appearance.shadowColor = UIColor(Color.audi.barTopSeparator)
appearance.setBackIndicatorImage(UIImage(named: "back-small")!, transitionMaskImage: UIImage(named: "back-small")!)
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().compactAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
}
static func transparentNavigationBar() {
appearance.configureWithTransparentBackground()
appearance.titleTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor(Color.audi.barContentOverlay),
NSAttributedString.Key.font: UIFont(name: Fonts.typeVFNormalBold.rawValue, size: 12)!
]
appearance.shadowColor = .clear
appearance.setBackIndicatorImage(UIImage(named: "back-white-small")!, transitionMaskImage: UIImage(named: "back-white-small")!)
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().compactAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
}
}
func setNavigationBarStyle(scrollY: CGFloat) {
if scrollY <= 0 {
UINavigationBar.transparentNavigationBar()
} else {
UINavigationBar.defaultNavigationBar()
}
}