Correspondence that the change after the initial setting of UINavigationBarAppearance
is not reflected
The other day, in iOS application development, I implemented a function to change the characters and background color of UINavigationBar according to the contentOffset of ScrollView, but I encountered a phenomenon that the change is not reflected on iOS/iPadOS14 or less, so I will take that correspondence as a memorandum.
How to reflect the setting change even after the initial setting of UINavigationBarAppearance
The way to apply the reconfiguration on iOS/iPadOS14 or below is to initialize the configuration. An example of the original implementation is code like this
func setupNavitaionBar(alpha: CGFloat) { // <- T value `alpha` is depending on scrollView's contentOffset.y value
guard let navigationBar = navigationController?.navigationBar else { return }
let backgroundColor = UIColor.white.withAlphaComponent(alpha)
let titleColor = UIColor.black.withAlphaComponent(alpha)
let appearance = UINavigationBarAppearance()
appearance.backgroundColor = backgroundColor
appearance.titleTextAttributes = [.foregroundColor: titleColor]
navigationBar.standardAppearance = appearance
}
The above code changes the transparency of the text and background color of the navigationBar according to the value of alpha, so every time you call setupNavitaionBar
, the UI of the navigationBar changes according to the value of alpha.
However, in the above code, on devices with iOS/iPadOS14 or lower, the setting is applied only once at the first time, and the execution part after the second time is not applied well.
Therefore, modify it as follows.
func setupNavitaionBar(alpha: CGFloat) { // <- T value `alpha` is depending on scrollView's contentOffset.y value
guard let navigationBar = navigationController?.navigationBar else { return }
let backgroundColor = UIColor.white.withAlphaComponent(alpha)
let titleColor = UIColor.black.withAlphaComponent(alpha)
let appearance = UINavigationBarAppearance()
appearance.backgroundColor = backgroundColor
appearance.titleTextAttributes = [.foregroundColor: titleColor]
// Add codes to reset navigationBar appearance config.
if #available(iOS 15.0, *) {
} else {
navigationBar.standardAppearance.configureWithDefaultBackground()
}
navigationBar.standardAppearance = appearance
}
As mentioned above, by calling configureWithDefaultBackground
and initializing the settings, the setting changes from the second time onward will also be reflected (I do not know the reason).