Milan Nosáľ Milan Nosáľ - 3 years ago 239
Swift Question

How to mimic `UITableViewController` showing of the large titles in `navigationBar` on iOS 11

I'm trying to use

prefersLargeTitles
from iOS 11 in my application. It works as expected in subclasses of
UITableViewController
:

navigationController?.navigationBar.prefersLargeTitles = true


However, in one case I needed to subclass
UIViewController
and add a table view myself. In this situation I needed to constraint the table to the view myself:

tableView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.otherView.topAnchor).isActive = true


While these constraints present the
tableView
as I would expect, now the navigation bar always uses large title. I would like to mimic the behavior of the
UITableViewController
, so that when the
tableView
is scrolled to top, the large title is presented, otherwise the title collapses into the normal one.

How to solve this?

Answer Source

Seems that I have been able to emulate this behavior more or less closely enough. Implementing the delegate method for the tableView that reacts to scrolling, and then running the code that uses current contentOffset to either show, or hide the large title (UITableView inherits from UIScrollView, so the scrollView parameter refers in this case to the tableView):

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.y <= 0 {
        self.navigationItem.largeTitleDisplayMode = .always
    } else {
        self.navigationItem.largeTitleDisplayMode = .never
    }
    self.navigationController?.navigationBar.setNeedsLayout()
    self.view.setNeedsLayout()
    UIView.animate(withDuration: 0.25, animations: {
        self.navigationController?.navigationBar.layoutIfNeeded()
        self.view.layoutIfNeeded()
    })
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download