UISearchBar subview of UITableViewHeader?

只谈情不闲聊 提交于 2019-12-04 23:38:48

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/27512738/uisearchbar-subview-of-uitableviewheader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!