2017-02-23 16 views
0
import UIKit 

class ViewController: UIViewController, UITableViewDataSource, UISearchBarDelegate { 

@IBOutlet weak var tableView: UITableView! 
@IBOutlet weak var searchBar: UISearchBar! 

var filteredStates = [State]() 


var states = [ 

    State(stateName: "Alabama", abbreviation: "AL"), 
    State(stateName: "Alaska", abbreviation: "AK"), 
    State(stateName: "Arizona", abbreviation: "AZ"), 
    State(stateName: "Arkansas", abbreviation: "AR"), 
    State(stateName: "California", abbreviation: "CA"), 
    State(stateName: "Colorado", abbreviation: "CO"), 
    State(stateName: "Connecticut", abbreviation: "CT"), 

] 




override func viewDidLoad() { 
    super.viewDidLoad() 

    tableView.dataSource = self 
    searchBar.delegate = self 
    filteredStates = states 



    let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap)) 
    tableView.addGestureRecognizer(tap) 



} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 

} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as UITableViewCell 

    let state = states[indexPath.row] 

    cell.textLabel?.text = state.stateName 

    cell.detailTextLabel?.text = state.abbreviation 

    return cell 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    return filteredStates.count 
} 


// This method updates filteredData based on the text in the Search Box 
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { 


    filteredStates = searchText.isEmpty ? states : states.filter { (item: State) -> Bool in 

    return item.stateName.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil 


    } 

    print(filteredStates) 

    tableView.reloadData() 
} 


// Wehn search bar being editing, cancel button pops up 
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { 

    self.searchBar.showsCancelButton = true 

} 

// When search bar cancel button clicked 
// Cancel button dismiss, search text is empty, keyboard dismiss 
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { 

    searchBar.showsCancelButton = false 
    searchBar.text = "" 
    searchBar.resignFirstResponder() 

} 

// when click outside of keyboard 
// Keyboard dismiss 
func handleTap() { 

    self.view.endEditing(true) 

} 

// When clicked search button 
// keyboard dismiss 
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { 

    searchBar.resignFirstResponder() 

} 



} 

フィルタが正しく動作していません。私がどこで間違っていたかわからない。私は関数searchBar関数で何かが間違っているかもしれないと思う。検索のフィルタが正しく機能していません

The filter is not working correct

The filter is not working correct2

+0

問題を解決しましたか? –

+0

@Nirav Dいいえ、まだそれを理解しようとしています。 – QQ10

+0

新しいtableViewメソッドコードで質問を編集することもできます。 –

答えて

1

を切り替えるブールisActiveを確認することができ、私は少しあなたのコードを変更し、filterで使用含まれており、UISearchBarのデリゲートメソッドでいくつかの変更を行い、すべてとfilteredStatesを使用していました方法はUITableViewDataSourceです。

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate { 


    @IBOutlet weak var tableView: UITableView! 
    @IBOutlet weak var searchBar: UISearchBar! 

    var filteredStates = [State]() 


    var states = [ 

     State(stateName: "Alabama", abbreviation: "AL"), 
     State(stateName: "Alaska", abbreviation: "AK"), 
     State(stateName: "Arizona", abbreviation: "AZ"), 
     State(stateName: "Arkansas", abbreviation: "AR"), 
     State(stateName: "California", abbreviation: "CA"), 
     State(stateName: "Colorado", abbreviation: "CO"), 
     State(stateName: "Connecticut", abbreviation: "CT"), 

     ] 


    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Do any additional setup after loading the view. 
     filteredStates = states 
    } 

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

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell")! 
     //Access data from filteredStates array not from states array 
     cell.textLabel?.text = self.filteredStates[indexPath.row].stateName 
     cell.detailTextLabel?.text = self.filteredStates[indexPath.row].abbreviation 
     return cell 
    } 

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
     print(self.filteredStates[indexPath.row].stateName) 
    } 

    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { 
     searchBar.showsCancelButton = true 
    } 

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { 
     self.filteredStates = searchText.isEmpty ? states : states.filter({ $0.stateName.localizedCaseInsensitiveContains(searchText) }) 
     self.tableView.reloadData() 
    } 
    func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) { 
     searchBar.resignFirstResponder() 
    } 

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { 
     searchBar.resignFirstResponder() 
     searchBar.showsCancelButton = false 
     searchBar.text = "" 
     self.filteredStates = states 
     self.tableView.reloadData() 
    } 
} 

注:私はTapGestureように追加するのを忘れていないと、使用しているコードを追加していません。

+0

こんにちは、私はこのコードで空のテーブルビューを得ました。私のデータstateNameと省略形はテーブルビューに表示されませんでした。 – QQ10

+0

@ QQ10ストーリーボードで 'tableView'のデリゲートとデータソースを設定しました。ストーリーボードに設定していない場合は、前と同じ方法で' viewDidLoad'に設定してください。 –

+0

はい、はい私はそれが必要です!それは今働きます!私は数日の間、検索バーのフィルター機能に立ち往生しています。あなたの助けと貴重な時間をありがとう! – QQ10

0

検索かどうかを示すためにブール(例えば。isActive)を作成し、あなたのsearchBar: textDidChange方法

にフィルタロジックを実装し、検索値

を保存するために別の配列を作成します。起こったかキャンセルしたのはsearchBarShouldBeginEditingsearchBarCancelButtonClicked

あなたの cellForRowで3210

、あなたがlet state = states[indexPath.row]let state = filteredStates[indexPath.row]

+0

私のコードを更新しました。あなたは見てみることができますか? – QQ10

+0

@ QQ10あなたの商品は状態タイプ – Tj3n

+0

であるので、それは 'item:State'でなければなりません。それは状態タイプでなければなりません。今、私は2行目に別のエラーがあります。タイプ '状態'の値にメンバー '範囲'がないことを示します。これが意味するものではありません。 – QQ10

関連する問題