2017-10-02 2 views
0

J'ai référencé https://shrikar.com/swift-ios-tutorial-uisearchbar-and-uisearchbardelegate/ pour savoir comment fonctionne searchBar. J'ai suivi au tee, mais en tapant quelque chose dans le searchBar, il ne filtre pas les résultats. Voici le code. Peux-tu aider s'il te plait? Merci.searchBar ne recherchant pas et ne filtrant pas

import UIKit 

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate { 

    @IBOutlet weak var tableView: UITableView! 


    @IBOutlet weak var searchBar: UISearchBar! 

    var searchActive : Bool = false 
    var data = ["San Francisco","New York","San Jose","Chicago","Los Angeles","Austin","Seattle"] 
    var filtered:[String] = [] 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     /* Setup delegates */ 
     tableView.delegate = self 
     tableView.dataSource = self 
     searchBar.delegate = self 

    } 

    func searchBarTextDidBeginEditing(searchBar: UISearchBar) { 
     searchActive = true; 
    } 

    func searchBarTextDidEndEditing(searchBar: UISearchBar) { 
     searchActive = false; 
    } 

    func searchBarCancelButtonClicked(searchBar: UISearchBar) { 
     searchActive = false; 
    } 

    func searchBarSearchButtonClicked(searchBar: UISearchBar) { 
     searchActive = false; 
    } 

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

     filtered = data.filter({ (text) -> Bool in 
      let tmp: NSString = text as NSString 
      let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive) 
      return range.location != NSNotFound 
     }) 
     if(filtered.count == 0){ 
      searchActive = false; 
     } else { 
      searchActive = true; 
     } 
     self.tableView.reloadData() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


    func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 1 
    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     if(searchActive) { 
      return filtered.count 
     } 
     return data.count; 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! UITableViewCell; 
     if(searchActive){ 
      cell.textLabel?.text = filtered[indexPath.row] 
     } else { 
      cell.textLabel?.text = data[indexPath.row]; 
     } 

     return cell; 
    } 
} 
+0

si vous êtes sur 3, il devrait être func searchBar (_ searchBar: UISearchBar, textDidChange searchText: String) – koropok

Répondre

0

J'ai trouvé ma réponse à cette question. J'ai dû supprimer les liaisons pour l'IBOutlet pour searchBar et tableView. Ensuite, j'ai dû les rajouter à nouveau. Je ne sais pas pourquoi c'est comme ça, mais ça a vraiment marché.