我的故事板中的视图控制器上有一个UISearchBar和一个UITableView。搜索栏位于tableview上方,因此不会滚动。我的问题是UISearchController的初始化创建了自己的SearchBar实例,该实例与我在故事板上手动添加和定位的实例不同。
如何将我的故事板SearchBar设置为我的UISearchController为我创建的那个?
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
}
}
答案 0 :(得分:2)
您不能使用UISearchController
在故事板上放置的搜索栏,因为UISearchController提供了自己的故事板。
作为替代方案,请使用UIView
替换故事板中的搜索栏,然后将UISearchController
提供的搜索栏添加为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)
}
}
这会给你相同的行为。