Class Category to prevent a UISearchDisplayController from hiding the navigation bar

Annoyingly, the “right” method of calling setNavigationBarHidden:animated when the search begins will hide the bar, then show it. This is the only solution that isn’t ugly.

Original Source: Stack Overflow

Code below, modified so that it actually works (The super call in the linked question causes a crash so I took it out, and I used an inline Class Cateogry, DoNotHideBar, to avoid making a new file just to overwrite this one function):

@implementation UISearchDisplayController (DoNotHideBar)
- (void)setActive:(BOOL)visible animated:(BOOL)animated;
{
    if(self.active == visible) return;
    [self.searchContentsController.navigationController setNavigationBarHidden:YES animated:NO];
    [self.searchContentsController.navigationController setNavigationBarHidden:NO animated:NO];
    if (visible) {
        [self.searchBar becomeFirstResponder];
    } else {
        [self.searchBar resignFirstResponder];
    }
}
@end
Leave a comment

2 Comments.

  1. Hey, I’m trying to implement this, but only do so on certain view controllers. Whenever I put this in my code, every view with a search display controller behaves the same way. Any ideas?

  2. michael manesh

    I ended up switching to using this code on a UIViewController that implemented UISearchBarDelegate:

    - (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
    - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    }

    I have learned since writing this post that Class Categories are usually the wrong answer for implementing custom display functionality, specifically because it’s harder to keep changes from propagating to places you don’t want.