2016-03-20 145 views
0

我有一個數組,我試圖做一個實時搜索。所以最初我會有未經過濾的數組,當我搜索表格視圖時會更新我輸入的內容。我已經設置了代表,所以我迷失在爲什麼它不工作。任何幫助表示讚賞:)爲什麼搜索不起作用?

@IBOutlet weak var table: UITableView! 
var searchController = UISearchController() 
var unfilitered = ["cat", "dog", "bat", "tiger"] 
var filtered = [String]() 
var shouldShowSearchResults = false 

override func viewDidLoad() { 
    super.viewDidLoad() 

    configureSearchController() 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    var cell: searchcell = table.dequeueReusableCellWithIdentifier("CELL") as! searchcell 

    if shouldShowSearchResults { 
     cell.animal.text = filtered[indexPath.row] 
    } 
    else { 
     cell.animal.text = unfiltered[indexPath.row] 
    } 

    return cell 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    if shouldShowSearchResults { 
     return filtered.count 
    } 
    else { 
     return unfiltered.count 
    } 
} 

func configureSearchController() { 
    searchController.searchBar.delegate = self 
    searchController.searchResultsUpdater = self 
    searchController.dimsBackgroundDuringPresentation = false 
    searchController = UISearchController(searchResultsController: nil) 
    searchController.searchBar.placeholder = "Search" 
    searchController.searchBar.sizeToFit() 
    table.tableHeaderView = searchController.searchBar 
} 

func searchBarTextDidBeginEditing(searchBar: UISearchBar) { 
    shouldShowSearchResults = true 
    table.reloadData() 
} 


func searchBarCancelButtonClicked(searchBar: UISearchBar) { 
    shouldShowSearchResults = false 
    table.reloadData() 
} 

func searchBarSearchButtonClicked(searchBar: UISearchBar) { 
    if !shouldShowSearchResults { 
     shouldShowSearchResults = true 
     table.reloadData() 
    } 

    searchController.searchBar.resignFirstResponder() 
} 

func updateSearchResultsForSearchController(searchController: UISearchController) { 
    let searchString = searchController.searchBar.text 


    filtered = unfiltered.filter({ (animal) -> Bool in 
     let animalText: NSString = animal 

     return (animalText.rangeOfString(searchString!, options: NSStringCompareOptions.CaseInsensitiveSearch).location) != NSNotFound 
    }) 

    table.reloadData() 
} 
+0

你確定'filtered'包含你想要的嗎?是否調用了updateSearchResultsForSearchController? – Michael

+0

我剛剛添加了幾個斷點並進行了檢查,並且沒有調用DidBeginEditing。 – user6032625

+0

聽起來像你沒有設置'UITextField'的委託。你可以在'updateSearchResultsForSearchController'中設置'shouldShowSearchResults'。 – Michael

回答

0

reloadData方法不會強制重繪tableView,除非它在主線程上執行。

+0

因此,在'upadteSearchResultsForSearchController'在主線程上運行table.reloadData? – user6032625

+0

是的。 Objective-C中的[table performSelectorOnMainThread:@selector(reloadData)]'。 (對我的Swift技能沒有足夠的信心在Swift中寫出來,對不起。) –