It seems that using a negative content offset is the way to go.
I really like the idea of Demosthese to keep track of the biggest top inset.
However, there is a problem with this approach.
Sometime large titles cannot be displayed, for example, when an iPhone is in landscape mode.
If this method is used after a device has been rotated to landscape then the offset of the table will be too much because the large title is not displayed in the navigation bar.
An improvements to this technique is to consider biggestTopSafeAreaInset only when the navigation bar can display a large title.
Now the problem is to understand when a navigation bar can display a large title.
I did some test on different devices and it seems that large titles are not displayed when the vertical size class is compact.
So, Demosthese solution can be improved in this way:
class TableViewController: UITableViewController {
var biggestTopSafeAreaInset: CGFloat = 0
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
self.biggestTopSafeAreaInset = max(view.safeAreaInsets.top, biggestTopSafeAreaInset)
}
func scrollToTop(animated: Bool) {
if traitCollection.verticalSizeClass == .compact {
tableView.setContentOffset(CGPoint(x: 0, y: -view.safeAreaInsets.top), animated: animated)
} else {
tableView.setContentOffset(CGPoint(x: 0, y: -biggestTopSafeAreaInset), animated: animated)
}
}
}
There is still a case that could cause the large title to not be displayed after the scroll.
If the user:
- Open the app with the device rotated in landscape mode.
- Scroll the view.
- Rotate the device in portrait.
At this point biggestTopSafeAreaInset has not yet had a chance to find the greatest value and if the scrollToTop method is called the large title will be not displayed.
Fortunately, this is a case that shouldn't happen often.