Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchBar subview of UITableViewHeader?

I want to add a UISearchBar to a UITableView that already has a header view. When I try and add the search bar to the existing header view it works until I tap on it, at which point I get The view hierarchy is not prepared for the constraint, which appears to be because the search bar is not a direct subview of the tableview so when the UISearchController tries to update the constraints it can't.

The only way around this that I've found is making the table view header the search bar, then everything works fine, but of course then I lose the other views that were already in the header view.

like image 459
hokiewalrus Avatar asked Dec 16 '14 19:12

hokiewalrus


Video Answer


1 Answers

To get around this behavior, I put my search bar in a container UIView. Apply the constraints to this container view and use an autoresizing mask for the search bar within the container.

// Configure header view
UIView *headerView = ...
...

// Create container view for search bar
UIView *searchBarContainer = [UIView new];
searchBarContainer.translatesAutoresizingMaskIntoConstraints = NO;
[searchBarContainer addSubview:self.searchBar];
[headerView addSubview:searchBarContainer];
self.searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

// Apply constraints involving searchBarContainer
[headerView addConstraint: ...];
...

// Then add header to table view
self.tableView.tableHeaderView = headerView;
like image 132
Kiefer Aguilar Avatar answered Oct 17 '22 20:10

Kiefer Aguilar