12

I have a table view with a search bar on top of it. My requirement is to do not show the search bar when someone open the page but when someone slides the table down then the search bar should be visible.

Abhinav
  • 37,684
  • 43
  • 191
  • 309

2 Answers2

23

In your controller's viewDidAppear: method, set the contentOffset property (in UIScrollView) of your table view to hide the search bar.

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];    
    self.tableView.contentOffset = CGPointMake(0, SEARCH_BAR_HEIGHT);
}
murat
  • 4,893
  • 4
  • 31
  • 29
  • 11
    Using viewDidAppear: can cause the contentOffset change to happen visibly to the user of the app. Using viewWillAppear: will make the change before anything is displayed to the user. – Shoerob Mar 18 '13 at 19:42
  • 3
    You can also do this in `viewDidLoad` to do it just once initially, and still remember your place in the tableView when returning to the view (for example in a `UINavigationController`). – devios1 Mar 05 '15 at 19:29
4

Related to murat's answer, here's a more portable and correct version that will do away with animated offsetting on view load (it assumes the search bar has an outlet property called searchBar):

- (void)viewWillAppear:(BOOL)animated
{
    self.tableView.contentOffset = CGPointMake(0, self.searchBar.frame.size.height);
}

UPDATE:

To accommodate tapping on the search icon in the section index, the following method needs to be implemented, which restores the content offset:

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title
               atIndex:(NSInteger)index
{
    index--;
    if (index < 0) {
        [tableView
            setContentOffset:CGPointMake(0.0, -tableView.contentInset.top)];
        return NSNotFound;
    }
    return index;
}
Community
  • 1
  • 1
Gingi
  • 2,149
  • 1
  • 18
  • 34