UISearchBar in UITableViewController?

删除回忆录丶 提交于 2019-12-04 08:16:39

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.

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.

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;
}

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!