在 iOS 11 中,您可以使用几行代码将 UISearchController 放入 NavigationBar。
我在 ViewController.swift 中设置了所有内容。
func setupNavBar() {
navigationController?.navigationBar.prefersLargeTitles = true
let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = wordViewController
searchController.searchBar.scopeButtonTitles = ["French", "English"]
searchController.searchBar.delegate = wordViewController
navigationItem.searchController = searchController
// Make searchbar persistent
navigationItem.hidesSearchBarWhenScrolling = false
}
在我的委托(delegate)中,搜索会正确触发和过滤。但是,如果我单击任一范围按钮,它们就会消失。永远不会调用此委托(delegate)方法。 (按范围过滤还没有真正实现)
extension WordViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
if let searchText = searchBar.text {
print("Scoped changed: \(searchText)")
filteredWordList = wordList.filter({$0.contains(searchText)})
}
}
}
完整源代码在 Github 上:
https://github.com/melling/ios_topics/tree/master/NavBarSearch https://github.com/melling/ios_topics/tree/master/NavBarSearch/NavBarSearch
最佳答案
尝试在 setupNavBar() 中添加此代码:
searchController.dimsBackgroundDuringPresentation = false
关于带有范围按钮的导航栏中的 iOS 11 搜索 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45683725/