Reputation: 3819
I'm having a difficult time trying to implement updateSearchResultsForSearchController
in a UISearchController
. 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:
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()
}
I'm just a bit confused on how to use my data
to return back the correct searched results in updateSearchResultsForSearchController
.
Can someone point me in the right direction?
Thanks
Upvotes: 0
Views: 75
Reputation: 23451
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 { $0.name.containsString(searchedData) }
tableView.reloadData()
}
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.
Upvotes: 2