Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchBar in UITableViewController?

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

like image 437
SticksNStones Avatar asked Nov 14 '10 17:11

SticksNStones


3 Answers

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.

like image 154
Retterdesdialogs Avatar answered Nov 10 '22 09:11

Retterdesdialogs


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.

like image 38
Harikrishna Pai Avatar answered Nov 10 '22 10:11

Harikrishna Pai


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;
}
like image 4
Skela Avatar answered Nov 10 '22 09:11

Skela