Search code examples
objective-cuisearchbaruisearchcontroller

Show UISearchController on UITableView scroll down


I have a UISearchController just over my UITableView and my table has many recrods. When a user goes to bottom in the table, he has to come back to top to see the search bar. Below you can see how I create the search bar:

- (void) showSearchBar {
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];

    self.searchController.searchResultsUpdater = self;
    self.searchController.searchBar.placeholder = nil;
    [self.searchController.searchBar sizeToFit];
    self.tableView.tableHeaderView = self.searchController.searchBar;
    //self.sharedNavigationItem.titleView = _searchController.searchBar;

    self.searchController.delegate = self;
    self.searchController.dimsBackgroundDuringPresentation = NO; // default is YES
    self.searchController.searchBar.delegate = self; // so we can monitor text changes + others
        self.definesPresentationContext = YES;
    _searchController.hidesNavigationBarDuringPresentation = NO;

}

I was wondering how to show the search bar when I scroll down (go up) in the table and hide it back when I scroll up (go down) in the table even I am at the bottom of the table.


Solution

  • The search bar can be placed arbitrarily in the UI. Create a sibling view to the table view, placed -- for example -- above the table. Give that view a height constraint set initially to 44px and provide outlets to both the view and the constraint...

    @property(weak,nonatomic) IBOutlet UIView *searchBarContainerView;
    @property(weak,nonatomic) IBOutlet NSLayoutConstraint *searchBarHeightConstraint;
    

    Now, your setup code changes to:

    // ...
    self.searchBarHeightConstraint.constant = self.searchController.searchBar.bounds.size.height;
    [self.searchBarContainerView addSubview:self.searchController.searchBar];
    // ...