我正在尝试使用UISearchController在iOS 11中显示搜索栏和范围栏.
这是我用来设置搜索控制器的代码
let searchController = UISearchController(searchResultsController: nil)
searchController.delegate = self
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.showsScopeBar = true
searchController.searchBar.scopeButtonTitles = ["1", "2", "3", "4"]
searchController.searchBar.delegate = self
definesPresentationContext = true
我想要一个带有范围栏的搜索栏,它始终可见.
当视图控制器加载时,上面的代码工作正常,它会显示搜索栏和范围栏.
但是,一旦搜索控制器变为活动状态然后被解除,iOS就会在关闭搜索控制器时隐藏范围栏,它只显示搜索栏.
我尝试通过在didDismissSearchController中添加以下代码来解决此问题,但是范围栏和搜索栏位于彼此之上,而不是搜索栏下方的范围栏(如下图所示).将此代码添加到searchBarTextDidBeginEditing(_ searchBar:UISearchBar)或searchBarTextDidEndEditing(_ searchBar:UISearchBar)无效.
searchController.searchBar.showsScopeBar = true
searchController.searchBar.sizeToFit()
最佳答案 >尝试将此添加到搜索控制器设置:
searchController.sizeToFit()
>然后添加:
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
self.searchBar.sizeToFit()
return true
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
self.searchBar.sizeToFit()
return true
}
不要在搜索栏功能中放置searchController.searchBar.showsScopeBar = true.由于某种原因,这会产生问题.