如何使搜索栏与我的tableview一起使用?

时间:2019-01-22 17:03:25

标签: ios swift uitableview uisearchbar

我希望能够使用搜索栏在表格视图中进行搜索。

将数据加载到表视图中可以正常工作。我不知道如何完成我的searchBar功能,以便能够按名称搜索。

override func tableView(_ tableView: UITableView, cellForRowAt       indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath)
    var dic:Dictionary<String,String> = arrayData[indexPath.row] as!       Dictionary<String, String>

    let nameLb:UILabel = cell.viewWithTag(100) as! UILabel;

    nameLb.text = "\(dic["name"]!))"

    return cell;
}




   func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    if(searchText.isEmpty)
    {


    }
      else {



       }

    tableView.reloadData()
}

1 个答案:

答案 0 :(得分:1)

您需要维护两个数据结构;一个是您的实际数据,另一个是表视图的数据源。如果未提供搜索/查询,则将整个结果集提供给数据源。输入查询后,您将根据完整的数据集进行过滤,提取出匹配项,然后将该子集提供给数据源。

您还可以实现UISearchResultsUpdating协议,这会使事情变得更容易。

在我的情况下,我不维护两个结果集,因为我正在积极地访问网络以获取一组新的单个结果。但是,如果您已经加载了一次数据集,那么您可能希望采用两种结果集方法。

以下是一些示例代码:

import Foundation
import UIKit

class WinePickerViewController : UITableViewController, UISearchResultsUpdating {

    // MARK: - Properties
    var pickerDelegate: WinePickerDelegate?;
    var searchResults = [Wine]();

    let searchController = UISearchController(searchResultsController: nil);
    var lastSearchTerm: String! = "";
    var appDelegate : AppDelegate?;

    // MARK: - View Setup
    override func viewDidLoad() {
        super.viewDidLoad()

        searchController.searchResultsUpdater = self
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.sizeToFit()
        self.tableView.tableHeaderView = searchController.searchBar

        tableView.tableHeaderView = searchController.searchBar;
        definesPresentationContext = true
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);
        self.searchController.isActive = true
        self.perform(#selector(showKeyboard), with:nil, afterDelay:0.1);
    }

    func showKeyboard() {
        self.searchController.searchBar.becomeFirstResponder();
    }

    deinit {
        searchController.view!.removeFromSuperview();
    }

    func performSearch() {
        ServerInterface.shared.winesSearchByAutocomplete(self.lastSearchTerm) { error, response in
            if error == nil {
                if let result = response as [Wine]? {
                    self.searchResults = result;
                }
                self.tableView.reloadData();
            }
        };
    }

    func filterContentForSearchText(_ searchText: String, scope: String = "All") {
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(performSearch), object: nil)
        lastSearchTerm = searchText.lowercased();
        self.perform(#selector(performSearch), with: nil, afterDelay: 0.5)
    }

    func updateSearchResults(for searchController: UISearchController) {
        filterContentForSearchText(searchController.searchBar.text!)
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return searchResults.count;
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let wine = searchResults[indexPath.row];
        cell.textLabel?.text = wine.title();
        cell.detailTextLabel?.text = wine.code;
        cell.detailTextLabel?.textColor = UISettings.primaryTintColor
        return cell
    }


    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let wine = searchResults[indexPath.row];
        pickerDelegate?.didPickWine(wine);
    }

}