美文网首页
Swift - 使用UISearchController实现带搜

Swift - 使用UISearchController实现带搜

作者: 小驴拉磨 | 来源:发表于2020-06-23 19:28 被阅读0次

到了iOS8,苹果废除UISearchDisplayController,建议我们使用UISearchController配合UITableView来实现。我们可以把搜索条放在表格头部,或者放在页面顶部,还是很灵活的。下面通过代码演示如何使用UISearchController实现具有搜索功能的表格。

伪代码说明:

(1)这里对ViewController做了类扩展ViewControllerExtensions.swift,把UITableView和UISearchController的代理方法都写在扩展类里,使代码更加简洁。
(2)同时这里提供两个样例。分别对应两种搜索方式,一个是实时搜索(即每输入一个字符就搜索过滤一次结果)。一个是输入时不进行搜索,只有点击键盘上的搜索按钮后才开始搜索。


image.png

一、实时搜索


import UIKit

class ViewController: UIViewController
{
    
    //原始数据集
    let schoolArray = ["清华大学","北京大学","中国人民大学","北京交通大学","北京工业大学",
                       "北京航空航天大学","北京理工大学","北京科技大学","中国政法大学",
                       "中央财经大学","华北电力大学","北京体育大学","上海外国语大学","复旦大学",
                       "华东师范大学","上海大学","河北工业大学"]
     
    //搜索过滤后的结果集
    var searchArray:[String] = [String](){
        didSet  {self.tableView.reloadData()}
    }
    
    // tableView
    let tableView: UITableView =
    {
        let table = UITableView(frame: CGRect(x: 0, y: 20, width: UIScreen.main.bounds.size.width,
                                              height: UIScreen.main.bounds.size.height-20), style: .plain)
        table.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        return table
    }()
    
    // UISearchController
    let countrySearchController: UISearchController =
    {
        let controller = UISearchController(searchResultsController: nil)
        controller.hidesNavigationBarDuringPresentation = false
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.searchBarStyle = .minimal
        controller.searchBar.sizeToFit()
        return controller
    }()

    override func viewDidLoad()
    {
        super.viewDidLoad()
        /// 设置UI
        setupUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        self.tableView.reloadData()
    }

    /// 设置UI
    func setupUI()
    {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.tableHeaderView = self.countrySearchController.searchBar
        self.countrySearchController.searchResultsUpdater = self
        
        view.addSubview(tableView)
    }
    
}

extension ViewController: UITableViewDelegate, UITableViewDataSource
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        if self.countrySearchController.isActive {
            return self.searchArray.count
        } else {
            return self.schoolArray.count
        }
    }
     
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell",
                                                 for: indexPath)
         
        if self.countrySearchController.isActive {
            cell.textLabel?.text = self.searchArray[indexPath.row]
            return cell
        } else {
            cell.textLabel?.text = self.schoolArray[indexPath.row]
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

extension ViewController: UISearchResultsUpdating
{
    //实时进行搜索
    func updateSearchResults(for searchController: UISearchController)
    {
        self.searchArray = self.schoolArray.filter { (school) -> Bool in
            return school.contains(searchController.searchBar.text!)
        }
    }
}

二、点击搜索按钮后才进行搜索

注:需要设置self.countrySearchController.searchBar.delegate = self

import UIKit

class ViewController: UIViewController
{
    
    //原始数据集
    let schoolArray = ["清华大学","北京大学","中国人民大学","北京交通大学","北京工业大学",
                       "北京航空航天大学","北京理工大学","北京科技大学","中国政法大学",
                       "中央财经大学","华北电力大学","北京体育大学","上海外国语大学","复旦大学",
                       "华东师范大学","上海大学","河北工业大学"]
     
    //搜索过滤后的结果集
    var searchArray:[String] = [String](){
        didSet  {self.tableView.reloadData()}
    }
    
    // tableView
    let tableView: UITableView =
    {
        let table = UITableView(frame: CGRect(x: 0, y: 20, width: UIScreen.main.bounds.size.width,
                                              height: UIScreen.main.bounds.size.height-20), style: .plain)
        table.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        return table
    }()
    
    // UISearchController
    let countrySearchController: UISearchController =
    {
        let controller = UISearchController(searchResultsController: nil)
        controller.hidesNavigationBarDuringPresentation = false
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.searchBarStyle = .minimal
        controller.searchBar.sizeToFit()
        return controller
    }()

    override func viewDidLoad()
    {
        super.viewDidLoad()
        /// 设置UI
        setupUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        self.tableView.reloadData()
    }

    /// 设置UI
    func setupUI()
    {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.tableHeaderView = self.countrySearchController.searchBar
        self.countrySearchController.searchBar.delegate = self
        
        view.addSubview(tableView)
    }
    
}

//MARK:UITableViewDelegate & UITableViewDataSource
extension ViewController: UITableViewDelegate, UITableViewDataSource
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        if self.countrySearchController.isActive {
            return self.searchArray.count
        } else {
            return self.schoolArray.count
        }
    }
     
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell",
                                                 for: indexPath)
         
        if self.countrySearchController.isActive {
            cell.textLabel?.text = self.searchArray[indexPath.row]
            return cell
        } else {
            cell.textLabel?.text = self.schoolArray[indexPath.row]
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

//MARK:UISearchBarDelegate
extension ViewController: UISearchBarDelegate
{
    //点击搜索按钮
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
    {
        self.searchArray = self.schoolArray.filter { (school) -> Bool in
            return school.contains(searchBar.text!)
        }
    }
     
    //点击取消按钮
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar)
    {
        self.searchArray = self.schoolArray
    }
}

原文出自:www.hangge.com 转载请保留原文链接:https://www.hangge.com/blog/cache/detail_797.html

相关文章

网友评论

      本文标题:Swift - 使用UISearchController实现带搜

      本文链接:https://www.haomeiwen.com/subject/jawhfktx.html