Unable to display UISearchBar if inside table view

My goal is to set the UISearchBar in the view right above the UITableView. When I set this to IB and then build, the table view expands to fill the entire window and the search bar is not visible. If I do a UISearchBar view of the UITableView, the search bar will appear as expected, but that’s not what I want. What I need is that after the user selects a row, I want to display a detailed view where the search bar remains on the screen. Therefore, I decided that this should be a separate subordination, and not part of the table. For some reason, however, I cannot show the search bar when it just represents a view outside the table.

+4
source share
2 answers

You must do this programmatically. Here is what I ended up doing. First add the following to the .h file of your ViewController.

@interface YourViewController : UITableViewController <UISearchBarDelegate> { UISearchBar *mySearchBar; } @property (nonatomic, retain) UISearchBar *mySearchBar; @end 

Then put this code in the viewDidLoad method of my RootViewController.

  self.mySearchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0, 64.0, self.view.bounds.size.width, 44.0)] autorelease]; self.mySearchBar.delegate = self; self.mySearchBar.showsCancelButton = YES; self.mySearchBar.hidden = YES; self.mySearchBar.tintColor = [UIColor lightGrayColor]; [self.navigationController.view addSubview: self.mySearchBar]; 

You may also need to add something like this to prevent the searchBar from being on top of your TableView.

  self.tableView.frame = CGRectMake(0.0, 44.0, 320, 324); 

In my case, the searchBar remained in the view when I expanded to the detailed view. I had to call:

  self.mySearchBar.hidden = YES;` 

In my didSelectRowAtIndexPath to get rid of it when I click on a cell.

+5
source

It does not work with UITableViewController. Here is what will give you the desired behavior:

 - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{ return search; //in .h, IBOutlet UISearchBar* search; } - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 44; } 
+1
source

All Articles