Samui
Samui

Reputation: 1384

UISearchBar in navigationbar

How can I show a UISearchBar in the NavigationBar?

I can't figure out how to do this.

Your help is very much appreciated.

Upvotes: 54

Views: 72392

Answers (5)

yoAlex5
yoAlex5

Reputation: 34175

Objective C code snippet for UISearchBar in NavigationBar

- (void)viewDidLoad {
    UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.searchController = searchController;
    } else {
        self.navigationItem.titleView = searchController.searchBar;
    }
}

Read more here

Upvotes: 2

Steve Moser
Steve Moser

Reputation: 7797

Check out Apple's UICatalog sample code. It shows how to use the new UISearchController in three different ways: modally, in nav bar, and below the navigation bar.

Upvotes: 11

djibouti33
djibouti33

Reputation: 12132

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];
    ...
}

Upvotes: 12

James Kuang
James Kuang

Reputation: 10730

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.

Upvotes: 20

Borut Tomazin
Borut Tomazin

Reputation: 8138

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;

Upvotes: 86

Related Questions