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

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

navigationController?.navigationBar.prefersLargeTitles = true

However, in one case I needed to subclass
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
as I would expect, now the navigation bar always uses large title. I would like to mimic the behavior of the
, so that when the
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
    UIView.animate(withDuration: 0.25, animations: {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download