1

I can't find a way to scroll a UIScrollView to the top in the same way the UIStatusBar does when the UINavigationItem contains a UISearchController. In that case, the scroll view scrolls to the top including showing the search bar. If I try to do this with the usual suspects (calling scroll, setting the content offset, etc.), I can't seem to make the search bar appearing.

Can I replicate programmatically what a tap on the UIStatusBar does?

trungduc
  • 11,926
  • 4
  • 31
  • 55
DrMickeyLauer
  • 4,455
  • 3
  • 31
  • 67

1 Answers1

1

In my opinion, I think Apple uses private API here to make it. But if you want to replicate something look like it, make the search bar appearing. You can follow step:

  • Scroll UIScrollView to top

    self.scrollView.contentOffset = CGPointZero;
    
  • After that, show search bar and large title

    // Show large title
    self.navigationItem.hidesSearchBarWhenScrolling = NO;
    // Show search bar
    self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
    
  • When search bar and large title are displayed, reset navigationItem properties to give scrollView normal behavior

    self.navigationItem.hidesSearchBarWhenScrolling = YES;
    self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAutomatic;
    

Result:

enter link description here

Working code:

[UIView animateWithDuration:0.25f animations:^{
  self.scrollView.contentOffset = CGPointZero;
} completion:^(BOOL finished) {
  [UIView animateWithDuration:0.25f animations:^{
    self.navigationItem.hidesSearchBarWhenScrolling = NO;
    self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
  } completion:^(BOOL finished) {
    self.navigationItem.hidesSearchBarWhenScrolling = YES;
    self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAutomatic;
  }];
}];

For more detail, you can take a look at my demo repo.

trungduc
  • 11,926
  • 4
  • 31
  • 55
  • Amazing, that does it! Thanks for the demo program. There is a tiny bit of flicker when the `UISearchBarController` reappears, but that's probably the best we can do with public APIs. Congratulations! – DrMickeyLauer Apr 11 '18 at 11:59
  • I should give answer sooner. I had intended to answer your question 2 days ago but I didn't because of that flicker. Finally, do it without receiving down vote. Thank you ;) – trungduc Apr 11 '18 at 12:21