iOS 表格检视标题中的搜寻列

示例

本示例使用搜索控制器来过滤表视图控制器中的单元格。搜索栏位于表格视图的标题视图内部。表格视图的内容以与搜索栏相同的高度偏移,因此首先隐藏了搜索栏。向上滚动超过表格视图的顶部边缘时,将显示搜索栏。然后,当搜索栏变为活动状态时,它会隐藏导航栏。

将UITableViewController嵌入到UINavigationController中,以获取UINavigationItem(包含导航栏)。然后将我们的自定义ViewController类设置为继承自UITableViewController并采用UISearchResultsUpdating协议。

class ViewController: UITableViewController, UISearchResultsUpdating {

    let entries = [(title: "Easiest", image: "green_circle"),
                   (title: "Intermediate", image: "blue_square"),
                   (title: "Advanced", image: "black_diamond"),
                   (title: "Expert Only", image: "double_black_diamond")]
    
    // 一个空的元组,将使用搜索结果进行更新。
    var searchResults : [(title: String, image: String)] = []
    
    let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()
        
       searchController.searchResultsUpdater= self
       self.definesPresentationContext= true

        // 将搜索栏放置在表格视图的标题中。
        self.tableView.tableHeaderView = searchController.searchBar

        // 将内容偏移设置为搜索栏高度的高度
        // 在首次显示视图时将其隐藏。
        self.tableView.contentOffset = CGPoint(x: 0, y: searchController.searchBar.frame.height)
    }
    
    func filterContent(for searchText: String) {
        // 使用匹配项更新searchResults数组
        // 在我们基于标题值的条目中。
        searchResults = entries.filter({ (title: String, image: String) -> Bool in
            let match = title.range(of: searchText, options: .caseInsensitive)
            // 如果范围包含匹配项,则返回元组。
            return match != nil
        })
    }

    // 标记:-UISearchResultsUpdating方法
    
    func updateSearchResults(for searchController: UISearchController) {
        // 如果搜索栏包含文本,请使用字符串过滤数据
        if let searchText = searchController.searchBar.text {
            filterContent(for: searchText)
            // 用搜索结果数据重新加载表视图。
            tableView.reloadData()
        }
    }

    // 标记:-UITableViewController方法
    
    override func numberOfSections(in tableView: UITableView) -> Int { return 1 }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // 如果搜索栏处于活动状态,请使用searchResults数据。
        returnsearchController.isActive?searchResults.count: entries.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 如果搜索栏处于活动状态,请使用searchResults数据。
        let entry =searchController.isActive? 
                    searchResults[indexPath.row] : entries[indexPath.row]
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = entry.title
        cell.imageView?.image = UIImage(named: entry.image)
        return cell
    }
}