您指的是UISearchController 的表示上下文。
Here is a linkdefinesPresentationContext 上的 Apple 文档以及我们关心的相关信息
此属性控制视图中的现有视图控制器
控制器层次结构实际上已被新内容覆盖
如果您还在使用之前的this example UISearchController,那么您已经差不多完成了,只需查看viewDidLoad() 内的以下代码行:
self.definesPresentationContext = true
默认值为false。由于它设置为 true,我们告诉UITableViewController,当视图控制器或其后代之一呈现视图控制器时,它将被覆盖。在我们的例子中,我们用 UISearchController 覆盖了 UITableViewController。
为了解决您的问题,隐藏 tableView/background 就像在搜索栏处于活动状态时清除或切换表格的数据源一样简单。这是在以下代码中处理的。
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.userSearchController.active) {
return self.searchUsers.count
} else {
// return normal data source count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("userCell") as! UserCell
if (self.userSearchController.active && self.searchUsers.count > indexPath.row) {
// bind data to the search data source
} else {
// bind data to the normal data source
}
return cell
}
当搜索栏被关闭时,我们要重新加载正常的数据源,方法如下:
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
// Clear any search criteria
searchBar.text = ""
// Force reload of table data from normal data source
}
这是 UISearchControllers 上的 link to a great article,还简要概述了它们的内部工作原理和视图层次结构。
对于未来关于 SO 的帖子,您应该始终尝试包含相关的代码示例,以便人们能够提供最好的反馈:)
编辑
我想我误解了你的问题,但以上内容仍然与答案相关。要在搜索结果为空或未输入任何内容时显示特殊视图,请执行以下操作:
1) 在情节提要中添加一个新的UIView 作为TableView 的子级UITableViewController 以及所需的标签/图像。这将在您可能拥有的任何原型单元旁边。
2) 在您的UITableViewController 中创建并连接插座
@IBOutlet var emptyView: UIView!
@IBOutlet weak var emptyViewLabel: UILabel!
3) 最初在viewDidLoad()中隐藏视图
self.emptyView?.hidden = true
4) 创建一个帮助函数来更新视图
func updateEmptyView() {
if (self.userSearchController.active) {
self.emptyViewLabel.text = "Empty search data source text"
self.emptyView?.hidden = (self.searchUsers.count > 0)
} else {
// Keep the emptyView hidden or update it to use along with the normal data source
//self.emptyViewLabel.text = "Empty normal data source text"
//self.emptyView?.hidden = (self.normalDataSource.count > 0)
}
}
5) 查询完毕后拨打updateEmptyView()
func loadSearchUsers(searchString: String) {
var query = PFUser.query()
// Filter by search string
query.whereKey("username", containsString: searchString)
self.searchActive = true
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if (error == nil) {
self.searchUsers.removeAll(keepCapacity: false)
self.searchUsers += objects as! [PFUser]
self.tableView.reloadData()
self.updateEmptyView()
} else {
// Log details of the failure
println("search query error: \(error) \(error!.userInfo!)")
}
self.searchActive = false
}
}
希望有帮助!