为什么搜索不起作用?

时间:2016-03-20 23:00:30

标签: ios swift uisearchbar

我有一个数组,我正在尝试进行实时搜索。所以最初我将拥有未经过滤的数组,因为我搜索表视图将在我输入时更新。我已经设置了代表,所以我很遗憾为什么它不起作用。任何帮助表示赞赏:)

@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()
}

1 个答案:

答案 0 :(得分:0)

reloadData方法不会强制重绘tableView,除非它在主线程上执行。