Search code examples
iosobjective-cuisearchbaruisearchcontroller

How to prevent the UISearchController from showing the navigation bar?


My use case is kind of strange. I'm using my own navigation bar, so I hide the default one with

[self.navigationController setNavigationBarHidden:YES animated:NO];

on viewWillAppear.

Everything works great, but if I have the keyboard open on an active search, and then I go back to a previous UIViewController, then the native navigation bar shows up again, and I end up with 2 navigation bars (my own and the default).

This is how I'm setting up my UISearchController in viewDidLoad:

- (void)viewDidLoad {
[super viewDidLoad];
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.obscuresBackgroundDuringPresentation = NO;
self.searchController.searchBar.delegate = self;
[self.searchController.searchBar sizeToFit];
self.definesPresentationContext = YES;
self.searchController.hidesNavigationBarDuringPresentation = YES;
self.searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
}

I already tried removing the self.definesPresentationContext = YES; (or turning it to NO), but that creates a different issue, which is that when I go back to the previous UIViewController the search bar stays on top of everything else! Until I tap on Cancel. I also tried calling the Cancel button programatically on viewWillDissappear, but that didn't work either...

So I'm running out of options, and that's why I'm here.

Any thoughts?


Solution

  • Using a navigation bar that is not the standard maybe it's not the best idea. (I know customers can sometimes be stubborn, but we should teach them that sometimes standard solutions have a lot of good points, like low maintenance for example, which turns in lower bills for them).

    Having said that, as a last resort I may suggest you a quite "strong" approach. You could subclass the UINavigationController with a custom class, and inside this class you could override the setNavigationBarHidden method like this

    - (void)setNavigationBarHidden:(BOOL)hidden animated:(BOOL)animated{
         [super setNavigationBarHidden:YES animated:NO];
    }
    

    method. This should make the bar hidden all the time. Still, i'm not a big supported of this kind of solutions, but it may work in your case.