UITearchBar UITableViewHeader的子视图?

hok*_*rus 6 uitableview uisearchbar ios uisearchcontroller

我想将UISearchBar添加到已经具有标题视图的UITableView.当我尝试将搜索栏添加到现有的标题视图时,它一直有效,直到我点击它,此时我得到The view hierarchy is not prepared for the constraint,这似乎是因为搜索栏不是tableview的直接子视图,所以当UISearchController尝试更新时它不能的约束.

我找到的唯一方法是将表视图标题作为搜索栏,然后一切正常,但当然我丢失了标题视图中已有的其他视图.

Kie*_*lar 4

为了解决这个问题,我将搜索栏放在一个容器中UIView。将约束应用于此容器视图,并为容器内的搜索栏使用自动调整大小掩码。

// 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;
Run Code Online (Sandbox Code Playgroud)