开发者

Adding UISearchBar as tableHeaderView in xib not works

开发者 https://www.devze.com 2023-04-09 13:34 出处:网络
I added UISearchBar as tableHeaderView for UITableView开发者_开发知识库 in xib, by just dropping UISearchBar onto UITableView.

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

Adding UISearchBar as tableHeaderView in xib not works


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号