在UISearchController中实现updateSearchResultsForSearchController时遇到问题?

时间:2016-05-01 20:05:11

标签: ios swift uisearchcontroller

我在updateSearchResultsForSearchController尝试实施UISearchController时遇到了困难。它与我如何实现原始数组有关。我不知道如何使用该数组来查找搜索到的文本。

以下是我的代码片段:

Test.swift:

struct Test
{
    let name: String
    let hobby: String
}

Main.swift:

var resultsSearchController = UISearchController()
var filteredData: [Test] = [Test]()

var data: [Test] = [Test]()

override func viewDidLoad()
{        
    resultsSearchController = UISearchController(searchResultsController: nil)
    definesPresentationContext = true
    resultsSearchController.dimsBackgroundDuringPresentation = true
    resultsSearchController.searchResultsUpdater = self
    tableView.tableHeaderView = resultsSearchController.searchBar

    data = [
    Test(name: "Abby", hobby: "Games"),
    Test(name: "Brian", hobby: "TV"),
    Test(name: "Ced", hobby: "Gym"),
    Test(name: "David", hobby: "Fun")]

    tableView.dataSource = self
    tableView.delegate = self
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    if (resultsSearchController.active && resultsSearchController.searchBar.text != "")
    {
        return filteredData.count
    }

    return data.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    var cell: UITableViewCell!

    // Dequeue the cell to load data
    cell = tableView.dequeueReusableCellWithIdentifier("Funny", forIndexPath: indexPath)

    let example: Test

    if resultsSearchController.active && resultsSearchController.searchBar.text != ""
    {
        example = filteredData[indexPath.row]
    }
    else
    {
        example = data[indexPath.row]
    }

    return cell
}

func updateSearchResultsForSearchController(searchController: UISearchController)
{
    filteredData.removeAll(keepCapacity: false)

    let searchPredicate = NSPredicate(format: "hobby CONTAINS[c] %@", resultsSearchController.searchBar.text!)

    // WHAT ELSE TO DO?

    tableView.reloadData()
}

我对如何使用dataupdateSearchResultsForSearchController中返回正确的搜索结果感到有些困惑。

有人能指出我正确的方向吗?

由于

1 个答案:

答案 0 :(得分:2)

您需要做什么才能在数据源中进行搜索并返回其他数据,如下代码:

func updateSearchResultsForSearchController(searchController: UISearchController) {

    filteredData.removeAll(keepCapacity: false)

    let searchedData = resultsSearchController.searchBar.text

    // find elements that contains the searchedData string for example
    filteredData = data.filter { $0.name.containsString(searchedData) }

    tableView.reloadData()
}

如果您想对struct的其他字段执行其他类型的搜索,则可以按照自己的喜好修改filter。一旦你致电tableView.reloadData(),所有人都将重新加载。

我希望这对你有所帮助。