4

My goal is to have a UISearchBar fixed in a view right above a UITableView. When I set this up in IB and then build, the table view expands to fill the whole window and the search bar is not visible. If I make the UISearchBar a subview of the UITableView, the search bar displays as expected, but this is not what I want. What I'm after is that after the user selects a row, I want to display a detail view with the search bar still remaining on the screen. So I figured it needed to be a separate subview, not part of the table. For some reason though, I can't can the search bar to display when it's simply a subview outside of the table.

2 Answers 2

5

You have to do this programatically. Here's 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 drilled down to a detail view. I had to call:

 self.mySearchBar.hidden = YES;` 

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Jonah. That got me where I need to go!
1

It doesn't work with UITableViewController. Here's what will give you desired behaviour:

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

3 Comments

Hi Poitr. Need a little more information on how this fits in with the code above or if it doesn't work with it at all. I'm trying to do this now. Thanks. Are you doing this in another controller or within the TVC?
Hmmm, Piotr this just puts the searchbar into the header, which is not good if you plan on using anything in the header.
Yes, and rather than using the search view straight away, you can instead build UIView containing search and any other elements.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.