iphone x:将搜索栏保持在安全区域内

iphone x: keep search bar within safe zone

正在升级我们的应用程序以支持 iPhone X。如何将搜索栏添加到 table 视图的 header 并将其置于安全区内?这是我们目前构建搜索栏的方式。

let searchController = UISearchController(searchResultsController: nil)
func buildSearchBar() {
    self.searchController.searchResultsUpdater = self
    self.searchController.hidesNavigationBarDuringPresentation = false
    self.searchController.dimsBackgroundDuringPresentation = false
    self.searchController.searchBar.sizeToFit()
    self.tableView.tableHeaderView = searchController.searchBar

    self.definesPresentationContext = true
}

不清楚 "within the safe zone" 是什么意思。 table 视图可以滚动,因此搜索栏不一定 "within" 屏幕的任何部分;它可以向上滚动到传感器区域后面和更远的地方。

但是,您会注意到,本机应用程序不会将搜索栏作为 table 的 header。他们把它放在导航栏中。你也应该这样做。通过设置navigationItem.

searchController将搜索栏放入导航栏

这个话题在 Building Apps for iPhone X video. (Designing for iPhone X 也是一个很好的视频中明确讨论。)

最重要的是,Apple 建议使用导航控制器并将其显示在那里:

let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false

if #available(iOS 11, *) {
    navigationItem.searchController = searchController
    searchController.isActive = true
} else {
    present(searchController, animated: true)
}

(顺便说一句,即使没有导航控制器,present-ing 搜索控制器,而不是将其设置为 table header,可以防止它不会滚出安全区域。)