UITableViewHeader的UISearchBar子视图?

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

解决这个问题的唯一方法就是将表格视图标题放在search栏中,然后一切正常,但是当然我会丢失已经在标题视图中的其他视图。

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

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