Pangu Pangu - 1 year ago 94
Swift Question

Having trouble implementing updateSearchResultsForSearchController in UISearchController?

I'm having a difficult time trying to implement

in a
. It has to do with how I implemented my original array. I'm not sure how to use that array to find the searched text.

Here's a snippet of my code:


struct Test
let name: String
let hobby: String


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.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.searchBar.text != ""
example = filteredData[indexPath.row]
example = data[indexPath.row]

return cell

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

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



I'm just a bit confused on how to use my
to return back the correct searched results in

Can someone point me in the right direction?


Answer Source

What do you need to to is make the search in your data source and return the data nothing else, something like this code:

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 { $ }


If you want to perform another type of search regarding another field of your struct you can modify the filter like you like. Once you call the tableView.reloadData() all is going to be reloaded again.

I hope this help you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download