从 iOS 15 上的非透明导航栏导航到具有透明导航栏的视图控制器

Navigating to a view controller with a transparent navigation bar from a non-transparent navigation bar on iOS 15

在 iOS15 上,当导航到具有透明导航栏的视图控制器时,透明栏的动画未按预期工作。

但是,如果您导航回带有透明导航栏的视图控制器,动画将按预期运行。

这是我设置视图控制器的方式:

rootVC

let appearance = UINavigationBarAppearance()
appearance.configureWithDefaultBackground()
appearance.backgroundColor = UIColor.red

self.navigationController?.navigationBar.standardAppearance = appearance
self.navigationController?.navigationBar.scrollEdgeAppearance = self.navigationController?.navigationBar.standardAppearance

firstVC

let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()

self.navigationController?.navigationBar.standardAppearance = appearance
self.navigationController?.navigationBar.scrollEdgeAppearance = self.navigationController?.navigationBar.standardAppearance

secondVC

let appearance = UINavigationBarAppearance()
appearance.configureWithDefaultBackground()
appearance.backgroundColor = UIColor.yellow

self.navigationController?.navigationBar.standardAppearance = appearance
self.navigationController?.navigationBar.scrollEdgeAppearance = self.navigationController?.navigationBar.standardAppearance

请注意以下示例中从 secondVC -> firstVC 而非 rootVC[ 的过渡是多么平滑=43=] -> firstVC:

示例项目:https://github.com/karlingen/NavigationTest

知道为什么会这样吗?

我收到 Apple 的以下回复:

You should get better behavior using per-item customization, that is setting these properties on their view controller’s UINavigationItem instead of on the UINavigationBar itself. This also frees you from the strict timing necessary for the viewWillAppear: approach to work – as long as your customizations are applied before the view controller is pushed, you should get a good transition. viewDidLoad is generally a good place to do these customizations when using the per-item customization support.

所以我们应该改用 UINavigationItem。 使用以下代码为我修复了它:

# firstVC.swift    
override func viewDidLoad() {
    let appearance = UINavigationBarAppearance()
    appearance.configureWithTransparentBackground()
    
    self.navigationItem.standardAppearance = appearance
    self.navigationItem.scrollEdgeAppearance = appearance
}