简体   繁体   中英

How to get search bar to work with my tableview?

I want to be able to search in my tableview using a search bar.

Loading data into the tableview works fine. I don't know how to complete my searchBar func in order to be able to search by name.

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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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