In my case, I am trying to implement search
functionality for my tableview
data. Here, I am loading JSON
data into my Tableview section
and rows
. In custom cell
I am showing name, I would like to create search by name. I tried below code but nothing display in my result. How to do in a proper way of search functionality.
var sections = [Section]()
var filteredNames = [Section]()
var searchController : UISearchController!
Tableview Delegates
// MARK: UITableview Delegates
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering {
return filteredNames[section].result.count
} else {
return sections[section].result.count
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].title
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell
let item = sections[indexPath.section].result[indexPath.row]
let filteritem = filteredNames[indexPath.section].result[indexPath.row]
if isFiltering {
cell.nameLabel.text = filteritem.name
} else {
cell.nameLabel.text = item.name
}
return cell
}
SearchBarAction and Delegates
// MARK: UISearchBar Delegates
@IBAction func searchAction(_ sender: Any) {
searchController = UISearchController(searchResultsController: nil)
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.keyboardType = UIKeyboardType.asciiCapable
searchController.searchBar.barTintColor = #colorLiteral(red: 0.317096545, green: 0.5791940689, blue: 0.3803742655, alpha: 1)
searchController.searchBar.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
searchController.dimsBackgroundDuringPresentation = false
// Make this class the delegate and present the search
self.searchController.searchBar.delegate = self
searchController.searchResultsUpdater = self
present(searchController, animated: true, completion: nil)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
guard let searchText = searchBar.text else {
isFiltering = false
return
}
filteredNames = sections[indexPath.section].result[indexPath.row].filter({
return $0.lowercased().contains(searchText.lowercased())
})
isFiltering = filteredNames.count > 0
self.tableView.reloadData()
}
Error: I am getting error - Use of unresolved identifier 'indexPath'; did you mean 'IndexPath'?