简体   繁体   English

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

[英]How to get search bar to work with my tableview?

I want to be able to search in my tableview using a search bar.我希望能够使用搜索栏在我的 tableview 中进行搜索。

Loading data into the tableview works fine.将数据加载到 tableview 工作正常。 I don't know how to complete my searchBar func in order to be able to search by name.我不知道如何完成我的 searchBar func 以便能够按名称搜索。

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()
}

You need to maintain two data structures;你需要维护两个数据结构; one is your actual data and the other is the datasource for your table view.一个是您的实际数据,另一个是您的表视图的数据源。 When no search/query is provided you feed the full result set to the datasource.当没有提供搜索/查询时,您将完整的结果集提供给数据源。 When a query is entered you filter against your full data set, extracting out the matches and then feeding that sub-set to your datasource.输入查询时,您可以根据完整数据集进行过滤,提取匹配项,然后将该子集提供给您的数据源。

You can also implement the UISearchResultsUpdating protocol which should make things easier.您还可以实现UISearchResultsUpdating协议,这将使事情变得更容易。

In my case I am not maintaining two result sets because I am actively hitting the network for a fresh set of single results.就我而言,我没有维护两个结果集,因为我正在积极访问网络以获取一组新的单个结果。 But if you have already loaded your data set once then you probably want to take the two result set approach.但是,如果您已经加载了一次数据集,那么您可能希望采用两个结果集的方法。

Here is some sample code:下面是一些示例代码:

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);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM