UISearchController

UISearchController:

A view controller that manages the display of search results d on interactions with a search bar.
管理搜索结果,集成了search bar

一个search控制器可以有两个自定义的控制器,一个用来显示可被搜索的内容,一个用来显示所有的结果

使用init(searchResultsController:)来传递显示结果的控制器,如果传递nil,表示使用当前的控制器来显示结果,也可以使用别的控制器

如在Displaying Searchable Content by Using a Search Controller中:

        resultsTableController = ResultsTableController()

        resultsTableController.tableView.delegate = self
        
        searchController = UISearchController(searchResultsController: resultsTableController)

每个search controller都提供了一个UISearchBar,当用户与search bar交互时,search控制器通知searchResultsUpdater对象,所以需遵循UISearchResultsUpdating协议

To customize the presentation or dismissal of the search results controller, assign an to the search controller’s delegate property. Delegate s must conform to the UISearchControllerDelegate protocol. You use the methods of that protocol to be notified when the search controller itself is activated and when the search results controller is presented or dismissed.
还有个delegate属性,遵循 UISearchControllerDelegate 协议

使用教程可参考:

一些说明:
1.设置searchResultsUpdater顺序,显示UISearchResultsUpdating协议的如下方法:

searchController.searchResultsUpdater = self
......

extension MasterViewController: UISearchResultsUpdating {
    
    func updateSearchResults(for searchController: UISearchController) {
        let searchBar = searchController.searchBar
        let scope = searchBar.scopeButton s![searchBar.selectedScopeButtonIndex]
        filterContentForSearchText(searchController.searchBar.text!, scope: scope)
    }
    
}

2.obscuresBackgroundDuringPresentation属性表示展示时是否有模糊背景

3.在iOS不同的版本中,注意使用的区别

        if #available(iOS 11.0, *) {
            // For iOS 11 and later, place the search bar in the navigation bar.
            // iOS11及以后的版本,把search bar放在navigation bar
            navigationItem.searchController = searchController
            
            // Make the search bar always visible.
            // 使search bar一直显示
            navigationItem.hidesSearchBarWhenScrolling = false
        } else {
            // For iOS 10 and earlier, place the search controller\'s search bar in the table view\'s header.
            // iOS10及以前的版本,把search controller的search bar 作为tableView的header
            tableView.tableHeaderView = searchController.searchBar
        }

4.设置scope

    // Setup the Scope Bar
    searchController.searchBar.scopeButton s = [\"All\", \"Chocolate\", \"Hard\", \"Other\"]
    searchController.searchBar.delegate = self

实现协议

extension MasterViewController: UISearchBarDelegate {
    // MARK: - UISearchBar Delegate
    func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
        filterContentForSearchText(searchBar.text!, scope: searchBar.scopeButton s![selectedScope])
    }
}

交互效果如下:

\"交互效果\"

收藏 打印