导航栏中带有范围按钮的 iOS11 SearchController

h4l*_*abs 5 ios swift ios11

在此输入图像描述

在 iOS 11 中,您可以使用几行代码将 UISearchController 放置在导航栏中。

我在 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
}
Run Code Online (Sandbox Code Playgroud)

在我的代表中,搜索会正确触发和过滤。但是,如果我单击任一范围按钮,它们就会消失。该委托方法永远不会被调用。(按范围过滤尚未实际实现)

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)})
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

完整源代码位于 Github 上:

https://github.com/melling/ios_topics/tree/master/NavBarSearch https://github.com/melling/ios_topics/tree/master/NavBarSearch/NavBarSearch

Art*_*nko 1

尝试在 setupNavBar() 中添加以下代码:

searchController.dimsBackgroundDuringPresentation = false
Run Code Online (Sandbox Code Playgroud)