2016-03-20 144 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中写出来,对不起。) –