5

I want to add a SearchBar to my TableView. I just dragged the UISearchBar to the header of an UITableView in IB, and it scrolled with my UITableView.

I changed to use UITableViewController now, and when I drag an UISearchBar in the header of the UITableView which is provided with the UITableViewController, it doesn't show up at all.

Is there a trick?

Kind regards

Sergey Kuryanov
  • 6,114
  • 30
  • 52
SticksNStones
  • 51
  • 1
  • 1
  • 3
  • Yes, there is a trick. When you drag and drop, carefully hover over the area you want to drop. The view will change size. When the size matches the size of your tableview, let go. You've found the right spot. I know this is a late response, but maybe it will help someone who tries doing it this way. – Victor Engel Feb 09 '19 at 15:22

5 Answers5

19

You can do it programmatically

UISearchBar *tempSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 0)];
self.searchBar = tempSearchBar;
[tempSearchBar release];
self.searchBar.delegate = self; 
[self.searchBar sizeToFit];  
self.tableView.tableHeaderView = self.searchBar;  

Hope this helps.

Retterdesdialogs
  • 3,180
  • 1
  • 21
  • 42
  • Great solution. To add a searchbar, I had to use UIViewController before. Now with our solution, I can use UITableViewController. – Wayne Lo Nov 17 '11 at 01:43
7

I get it to work by using two UITableViewDelegate Protocol methods –tableView:viewForHeaderInSection: and –tableView:heightForHeaderInSection: as given below.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        UISearchBar *tempSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 0)];
        [tempSearchBar sizeToFit];
        return tempSearchBar;
    }
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 40.0f;
    }
    return 0.1f;
}

Hope it helps.

Harikrishna Pai
  • 375
  • 4
  • 5
4

Whenever I define the searchbar in the nib, I dont add it to the table view's header on purpose. Instead I set it in the viewDidLoad function. Retterdesdialogs solution also works, so not sure why he hasn't got more votes.

- (void)viewDidLoad 
{
    [super viewDidLoad];
    tableView.tableHeaderView = searchBar;
}
Skela
  • 884
  • 10
  • 18
1

It also depends on how to initialized the tableview controller, if you alloc and init via initWithNib:Bundle method it should still show up. But with the tableview controller I think the default implementation method is initWithStyle. If you alloc'd and init with initWithStyle the nib file will never load.

863619
  • 11
  • 1
0

I just tried it and it worked for me, there shouldn't be a trick. If you want to post a distilled version of your project somewhere I can help you look.

Jlam
  • 1,932
  • 1
  • 21
  • 26