UISearchBar in navigationbar

To put searchBar into the center of navigationBar:

self.navigationItem.titleView = self.searchBarTop;

To put searchBar to the left/right side of navigationBar:

UIBarButtonItem *searchBarItem = [[UIBarButtonItem alloc] initWithCustomView:searchBar];
self.navigationItem.rightBarButtonItem = searchBarItem;

As of iOS 7, the UISearchDisplayController supports this by default. Set the UISearchDisplayController's displaysSearchBarInNavigationBar = YES to get this working easily.

Per the documentation:

Starting in iOS 7.0, you can use a search display controller with a navigation bar (an instance of the UINavigationBar class) by configuring the search display controller’s displaysSearchBarInNavigationBar and navigationItem properties.


As one commenter noted, using searchDisplayController.displaysSearchBarInNavigationBar = true ends up hiding any existing left/right bar button items.

I've found two different ways of adding a searchBar to a navigationBar using iOS7's new property on searchDisplayController.

1) Nib Based Approach

If you're using a .xib, you can set a User Defined Runtime Attribute for this value and for whatever reason, the leftBarButtonItem stays in tact. I have not tested it with a rightBarButtonItem.

enter image description here

2) Code (Timing Matters)

If you want to implement in code, timing seems to matter. It seems that you must add the searchBar to the navigationBar first, then set your barButtonItem.

- (void)viewDidLoad
{
    ...
    self.searchDisplayController.displaysSearchBarInNavigationBar = true;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem new];
    ...
}