swiftuiviewcontrolleruinavigationcontrolleruinavigationitemviewdidload

Swift How can I keep only the first page with a large title?


The large title of navigation item comes out when the app just describes execution. However, when I move to another page and come back, that mode is turned off. Create a viewDidLoad for each page as follows: What's the problem?

class CollectionViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    
    navigationController?.navigationBar.prefersLargeTitles = true
    self.navigationItem.largeTitleDisplayMode = .always
}

next page

class AssetCollectionViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    
    self.navigationItem.largeTitleDisplayMode = .never
}

Possibly adding code didn't work.

    override func viewDidDisappear(_ animated: Bool) {
    
    self.navigationItem.largeTitleDisplayMode = .always
}

Solution

  • How about doing all the implementation in your CollectionViewController like so:

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

    As apple says about viewDidLoad:

    This method is called after the view controller has loaded its view hierarchy into memory

    you should rather use viewWillAppear:

    This method is called before the view controller's view is about to be added to a view hierarchy and before any animations are configured for showing the view. You can override this method to perform custom tasks associated with displaying the view. For example, you might use this method to change the orientation or style of the status bar to coordinate with the orientation or style of the view being presented. If you override this method, you must call super at some point in your implementation.