Adding UISearchBar as tableHeaderView in xib does not work

I added the UISearchBar as a tableHeaderView for the UITableView in xib, just dropping the UISearchBar on the UITableView . It works fine when the table has more than 6 rows. But when the lines are less than 6 , then it UITableView does not scroll.

At the same time, if I add the UISearchBar as the tableHeaderView for the UITableView programmatically to the .m file using the following statement, EVERYTHING WORKS.

 tableViewTemp.tableHeaderView = searchBarFriends; 

It seems very strange to me, What could be the problem?

Please advise, thanks.

+7
source share
3 answers

Here is a little trick I did;) Don't make your SearchBar a subspecies of your UITableView. Just add them both to the nib file, and connect them to IBOutlets in your UITableViewController. Then what you are going to do is set the SearchBar as the title view for your table, so you don’t have to worry about overlapping frames and interfering with touch events. Here's how you do it:

Create Property in TableView Header File

 @property ( nonatomic, retain ) IBOutlet UISearchBar *searchBar; 

Define a header view for your table:

 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { return self.searchBar; // The property you wired up in IB } 

Set height for title or (UISearchBar)

 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 44; // The height of the search bar } 

That is all you need. Now this may not be the best solution if you have a grouped view of a table or a table with several partitions, but it is a simple solution for a simple table. Otherwise, you will need to adjust the frame of the search bar and the table in the code, because they overlap, and therefore you have problems with touching. Hope this helps!

+2
source

If you add a search bar as shown below, it will work

enter image description here

+1
source

I had almost the same problem (for me, it will not scroll at all with any number of lines, but it will be as soon as I remove the search bar). Fixed adding this parameter to viewDidLoad :

 self.tableView.alwaysBounceVertical = YES; 
0
source

All Articles