首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在UISearchController中实现UISearchController有困难吗?

在UISearchController中实现UISearchController有困难吗?
EN

Stack Overflow用户
提问于 2016-05-01 20:05:11
回答 1查看 68关注 0票数 0

我很难在UISearchController中实现UISearchController。这与我如何实现我的原始数组有关。我不知道如何使用这个数组找到搜索的文本。

下面是我的代码片段:

Test.swift:

代码语言:javascript
复制
struct Test
{
    let name: String
    let hobby: String
}

Main.swift:

代码语言:javascript
复制
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()
}

我只是有点困惑如何使用我的data返回updateSearchResultsForSearchController中正确的搜索结果。

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

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-01 20:21:35

您需要做的是在数据源中进行搜索,而不返回其他任何数据,如下代码所示:

代码语言:javascript
复制
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(),就会再次重新加载所有内容。

希望这能帮到你。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36971336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档