Search code examples
iosobjective-cuiscrollviewios11uisearchcontroller

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


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?


Solution

  • 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.