How to show/hide a search bar inside a navigation

2019-05-21 08:21发布

问题:

How to implement: I have UIBarButtonItem with a search icon, after I click on it, I want to show the search bar in navigation bar and on click cancel button in search bar, I want to show navigation bar without search and with buttons and title like in IOS 7 calendar app.

回答1:

Setup an action for your search button to present a UISearchController. See the Search > Present Over Navigation Bar demo in Apple's UICatalog sample code:

- (IBAction)searchButtonClicked:(UIBarButtonItem *)sender {
    // Create the search results view controller and use it for the UISearchController.
    AAPLSearchResultsViewController *searchResultsController = [self.storyboard instantiateViewControllerWithIdentifier:AAPLSearchResultsViewControllerStoryboardIdentifier];

    // Create the search controller and make it perform the results updating.
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
    self.searchController.searchResultsUpdater = searchResultsController;
    self.searchController.hidesNavigationBarDuringPresentation = NO;

    // Present the view controller.
    [self presentViewController:self.searchController animated:YES completion:nil];
}