2017-10-02 3 views
0

검색 막대의 작동 방법을 따르기 위해 https://shrikar.com/swift-ios-tutorial-uisearchbar-and-uisearchbardelegate/을 참조했습니다. 나는 티에 따라 갔지만 searchBar에 무언가를 타이핑 할 때 결과를 필터링하지 않습니다. 여기에 코드가 있습니다. 좀 도와 줄 수있어? 감사.searchBar가 검색 중이거나 필터링되지 않음

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

swift 3 인 경우 검색 막대가 있어야합니다 (_ searchBar : UISearchBar, textDidChange searchText : String). – koropok

답변

0

나는 내 대답을 발견했습니다. searchBar 및 tableView에 대한 IBOutlet의 바인딩을 삭제해야했습니다. 그런 다음 다시 추가해야했습니다. 이것이 왜 이렇게 좋은지는 모르지만 확실히 효과가있었습니다.

관련 문제