将UISearchBar放在tableview上方,但不能放在tableview或navbar中

我的故事板上的视图控制器上有一个UISearchBar和一个UITableView。 search栏在tableview上方,以便它不滚动。 我的问题是,UISearchController的初始化创build了自己的SearchBar实例,它与我手动添加和定位在我的故事板上的实例不一样。

如何将我的故事板SearchBar设置为由我的UISearchController为我创build的?

class ITSearchController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! // So that the search results are displayed in the current controllers table view let searchController = UISearchController(searchResultsController: nil) override func viewDidLoad() { searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false definesPresentationContext = true // This didn't work //var view = self.view.viewWithTag(777) //view = searchController.searchBar // This works but isn't what I want //tableView.tableHeaderView = searchController.searchBar // This works but places it in the nav section. Not what I want. // self.navigationItem.titleView = searchController.searchBar // This is what I want but doesn't work. Basically make the search bar on my storyboard equal to the one created. searchBar = searchController.searchBar } } 

由于UISearchController提供了它自己的故事板,因此不能使用放置在故事板上的search栏和UISearchController

作为替代方法,将故事板中的search栏replace为UIView ,然后将UISearchController提供的search栏作为子视图添加到该UIView

 class ITSearchController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchView: UIView! // make this UIView // So that the search results are displayed in the current controllers table view let searchController = UISearchController(searchResultsController: nil) override func viewDidLoad() { searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false definesPresentationContext = true // This should work searchView.addSubview(searchController.searchBar) } } 

这会给你相同的行为。