Mab KaaKoo
Mab KaaKoo

Reputation: 125

How display UISearchBar in UINavigation?

I have search icon in navigation bar, and UISearchBar in TableViewHeader. I want to hide UISearchBar but show and hide when:

UISearchbar show: Clicked on the search icon, then eliminate navigation and show it.

UISearchBar hide: Press cancel to hide search and display navigation back.

Please help me!!

Thank.

This is what I have done so far.

- (void) viewDidload{

self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
        self.searchBar.placeholder = @"Search";
self.searchBar.delegate = self;

[self.searchBar sizeToFit];

self.strongSearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
self.searchDisplayController.searchResultsDataSource = self;
self.searchDisplayController.searchResultsDelegate = self;
self.searchDisplayController.delegate = self;

self.tableView.tableHeaderView = self.searchBar;


_btnSearch = [UIButton buttonWithType:UIButtonTypeCustom];
_btnSearch.frame = CGRectMake(0, 0, 22, 22);
[_btnSearch setImage:[UIImage imageNamed:@"search_btn.png"] forState:UIControlStateNormal];
[_btnSearch addTarget:self action:@selector(showSearch:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithCustomView:_btnSearch];

self.navigationItem.rightBarButtonItems = _btnSearch;
}

This is my action when click on the iCon search

- (IBAction)showSearch:(id)sender{
    [self.searchBar becomeFirstResponder];
}

I don't want to place my search in tableView and how still I can display UISearchBar when click on search icon?

Another question: when I call [self.searchBar becomeFirstResponder]; it's doesn't work good. The cancel button doesn't work at all.

Please kindly help me.

Upvotes: 0

Views: 1144

Answers (1)

Mohammad Rabi
Mohammad Rabi

Reputation: 1412

to put searchBar into the center of navigationBar:

self.navigationItem.titleView = self.searchBar;

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

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

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

Upvotes: 4

Related Questions