Search code examples
uiscrollviewuitabbarcontrolleruinavigationbarios11uitabbar

Replicate UIScrollView's scrollToTop does not expand the UINavigationBar on UITabBar tap in iOS 11


(Similar to this question, which is unanswered: Tableview scroll to top not going all the way, as well as this one, also unanswered: Show navigation bar's large title and search bar on scroll to top collection view iOS 11 Swift 4)

I am trying to replicate scrolling to the top of a UITableView on status bar tap, but when I've tapped the UITabBar item and I'm already in that view. I have the tapping part working, but the scrolling to top is not working as I want it to.

The tableview is embedded in a navigationbar with large titles, and the searchbar is in the header, so it expands and collapses with scroll (the default behavior).

I am using the following to scroll, which, as expected, scrolls to the first table view cell, not expanding the navigation bar and/or the search bar:

[tv scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
          atScrollPosition:UITableViewScrollPositionTop animated:YES];

I can't seem to figure out how to scroll to the top and expand the navigation bar and the search bar. Manually calculating the content offset of the tableview doesn't work, as the offsets of the tableview are obviously different when the tableview is scrolled. Furthermore, I can't store the offset, as different screen sizes have different content offsets for an expanded navigationbar and searchbar.

Has anyone been able to figure this out?


Solution

  • Well, I'm a bit late to the action here but for future reference:

    For iOS 10+ (sufficient, since growing navigationBars were introduced in 11) you can use

    scrollView.perform(NSSelectorFromString("_scrollToTopIfPossible:"), with: true)
    

    This is private API. I've searched for a couple of hours and tried a lot of stuff but in the end this is the only thing that worked. Note that WhatsApp seems to be using the same method. Maybe they have a special deal with Apple or hide the api call (cough base64 cough).