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.
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;
链接地址: http://www.djcxy.com/p/55974.html