Adding UISearchBar as tableHeaderView in xib not works

I added UISearchBar as tableHeaderView for UITableView in xib, by just dropping UISearchBar onto UITableView . It is working fine, when the table has more than 6 rows. But when there is less than 6 rows, it UITableView does not scroll.

At the same time, if i add the UISearchBar as tableHeaderView for UITableView programatically in .m file using the following statement, EVERYTHING WORKS FINE.

tableViewTemp.tableHeaderView = searchBarFriends; 

Seems very strange to me, What might be the problem?

Please advice, Thank you.


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

Create the property in your TableView header file

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

Set the header view for your table:

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

Set the height for your header or (UISearchBar)

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

That's all you need. Now this may not be the best solution if you have a grouped tableview or a table with multiple sections but its a clean solution for a simple table. Otherwise, you'd have to adjust the frame of the searchbar AND the tableview in code because they overlap and thats why you have touch issues. Hope this helps!


if you add search bar like below hierarchy it will work

在这里输入图像描述


I had almost the same problem (for me it wouldn't scroll at all with any number of rows, but it would as soon as I removed the search bar). Fixed it adding this in viewDidLoad :

self.tableView.alwaysBounceVertical = YES;
链接地址: http://www.djcxy.com/p/9566.html

上一篇: jQuery如果复选框被选中

下一篇: 在xib中添加UISearchBar作为tableHeaderView不起作用