3

I have a view controller that is pushed onto a navigation stack. The stack has navigationBar.prefersLargeTitles = true, whilst this new view controller has navigationBar.prefersLargeTitles = false. I achieve this using the following code in the view controller that is pushed onto the stack:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    navigationController?.navigationBar.prefersLargeTitles = false
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    navigationController?.navigationBar.prefersLargeTitles = true
}

However, when I return back to the presenting view controller, the change in the navigation bar from navigationBar.prefersLargeTitles = false to navigationBar.prefersLargeTitles = true is a bit glitchy. Is there any way to make this smoother?

Many thanks

ajrlewis
  • 2,968
  • 3
  • 33
  • 67

1 Answers1

16

Instead of directly changing the preference via the navigation controller, you should change the behavior via the navigation item of the specific view controller you would like to affect.

// Root UIViewController
class ViewControllerA: UIViewController {

    override func viewDidLoad() {

        super.viewDidLoad()

        navigationController?.navigationBar.prefersLargeTitles = true
        navigationItem.largeTitleDisplayMode = .always
    }
}

// Pushed UIViewController
class ViewControllerB: UIViewController {

    override func viewDidLoad() {

        super.viewDidLoad()

        navigationItem.largeTitleDisplayMode = .never
    }
}

You can remove the lines you have in viewWillAppear and viewWillDisappear.

mkll
  • 2,058
  • 1
  • 15
  • 21
Callam
  • 11,409
  • 2
  • 34
  • 32
  • 1
    Nice thanks, this works. As `ViewControllerA` pushes `ViewControllerB`, the navigation bar shrinks in size and moves up vertically; it reveals the black "base" screen. Is it possible to change this black colour? Thanks – ajrlewis Sep 17 '18 at 08:07
  • @Callam In ViewControllerA I think you want `navigationController?.navigationBar.prefersLargeTitles = true` instead of `navigationItem.largeTitleDisplayMode = .always` According to the documentation for largeTitleDisplayMode: _"If the prefersLargeTitles property of the navigation bar is false, this property has no effect and the navigation item's title is always displayed as a small title."_ When setting `prefersLargeTitles = true` it isn't necessary to also set `largeTitleDisplayMode = .always` in this case - just tried this now. – Scott Carter Jul 06 '20 at 15:34