Animate a UINavigationBar's barTintColor

前端 未结 3 1377
[愿得一人]
[愿得一人] 2021-02-02 04:22

The app I\'m working on changes the barTintColor of its navigation bar when pushing new view controllers. Right now we set that colour in the destination view contr

3条回答
  •  伪装坚强ぢ
    2021-02-02 04:37

    Here is a simpler fix. The issue with barTintColor not animating correctly on pop occurs when you try to set the navigation bar appearance in viewWillDisappear. The fix is to set it in willMove(toParentViewController:) instead.

    The code below will produce a smooth fading transition during both push and pop, and regardless of whether it is initiated by a gesture or button tap. Tested on iOS 10 and 11.

    This also works for animating barStyle.

    import UIKit
    
    class RedViewController: UIViewController {
    
        override func viewWillAppear(_ animated: Bool) {
            self.title = "Red"
            self.navigationController?.navigationBar.barTintColor = .red
            self.navigationController?.navigationBar.tintColor = .white
        }
    
        override func willMove(toParentViewController parent: UIViewController?) {
            self.navigationController?.navigationBar.barTintColor = .white
            self.navigationController?.navigationBar.tintColor = nil
        }
    }
    

提交回复
热议问题