fengd
fengd

Reputation: 7569

UISearchBar inside a NavigationBar Get Deferenced When Keyboard Shows Up

I'm putting a search bar inside a navigation bar. here is the code

self.navigationBar =[[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 64)];
[self.view addSubview:self.navigationBar];

self.doneButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                           target:self
                                                           action:@selector(doneButtonPressed)];
self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 64)];
self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
self.searchBar.placeholder = @"Name of City";
self.searchBar.delegate = self;

self.searchController = [[UISearchDisplayController alloc]initWithSearchBar:self.searchBar contentsController:self];
self.searchController.delegate = self;
self.searchController.searchResultsDelegate = self;
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsTitle = @"Add Location";
self.searchController.displaysSearchBarInNavigationBar = YES;
self.searchController.navigationItem.rightBarButtonItems = @[self.doneButton];
self.navigationBar.items = @[self.searchController.navigationItem];

but the search bar behaves incorrectly.

enter image description here

I'm expecting it would look like this enter image description here

Upvotes: 0

Views: 1146

Answers (1)

fengd
fengd

Reputation: 7569

I've fixed this by bring the navigationBar to front after setting searchBar as the first responder

[self.searchController setActive:YES animated:NO];
[self.searchController.searchBar becomeFirstResponder];
[self.view bringSubviewToFront:self.navigationBar]; //this is the line I add

Upvotes: 1

Related Questions