0

I'm adding a search bar to the titleView of the navigationItem, so that it looks like this.

SearchBar in titleView of navigationItem

But when I tap on the search bar to get focus, it moves out of the screen and the keyboard is dismissed automatically, and then it looks like this.

searchbar out of screen

So, I'm neither able to type anything, nor see any results.

Here is my code where I am adding the search bar to the navigation item in viewDidLoad method.

self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0.0, 320.0, 44.0)];
self.searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
UIView *searchBarView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 310.0, 44.0)];
[self.searchBar setShowsCancelButton:NO animated:NO];
searchBarView.autoresizingMask = 0;


self.headSearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
self.headSearchDisplayController.delegate = self;
self.headSearchDisplayController.searchResultsDelegate = self;


self.headSearchDisplayController.searchResultsDataSource = self;
[searchBarView addSubview:self.searchBar];
self.searchBar.delegate = self;

self.navigationItem.titleView =searchBarView;

I tried it without setting the autoresizingmask, without any success. I am getting a hint that this behavior is happening because the search bar is in a view which is 44points, which is again inside the titleView. I am guessing that the searchResultsTableView doesn't have enough height to be seen, and thus we're only able to see the overlay. How do I solve this issue? Pointers in the right direction will be extremely helpful.

Here is an animated gif of the situation. enter image description here

Vignesh PT
  • 624
  • 12
  • 28

1 Answers1

0

I figured out that the Navigation bar was usually pushed up, when the search was focused, and since the search bar was in the navigation bar it was pushed up with it, and couldn't be visible on the screen.

I solved this by subclassing the UISearchDisplayController to hide the navigationBar. Here is the code.

#import "CustomSearchDisplayController.h"

@implementation CustomSearchDisplayController

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

Found this answer here: https://stackoverflow.com/a/3257456/1011042

Community
  • 1
  • 1
Vignesh PT
  • 624
  • 12
  • 28