Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. var locations = [Location]()
  2. var searchController:UISearchController!
  3. var searchResults = [Location]()
  4.  
  5. override func viewDidLoad() {
  6. super.viewDidLoad()
  7.  
  8. searchController = UISearchController(searchResultsController: nil)
  9. tableView.tableHeaderView = searchController.searchBar
  10. searchController.searchResultsUpdater = self
  11. searchController.dimsBackgroundDuringPresentation = false
  12.  
  13. self.tableView.reloadData()
  14. }
  15.  
  16. func filterContent(for searchText: String) {
  17.  
  18. searchResults = locations.filter({ (location) -> Bool in
  19. if let name = location.name {
  20. let isMatch = name.localizedCaseInsensitiveContains(searchText)
  21. return isMatch
  22. }
  23.  
  24. return false
  25.  
  26. })
  27.  
  28. }
  29.  
  30.  
  31. func updateSearchResults(for searchController: UISearchController) {
  32. if let searchText = searchController.searchBar.text {
  33. filterContent(for: searchText)
  34. tableView.reloadData()
  35. }
  36. }
  37.  
  38. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  39. if searchController != nil && searchController.isActive {
  40.  
  41. return searchResults.count
  42.  
  43. } else {
  44.  
  45. return locations.count
  46.  
  47. }
  48. }
  49.  
  50. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  51.  
  52. let cellIdentifier = "cell"
  53. let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! LocationTableViewCell
  54.  
  55. // The following line is where I receive the error, as I attempt to determine whether the app should get the result from the filtered search result
  56. let location = (searchController.isActive) ? searchResults[indexPath.row] : locations[indexPath.row]
  57.  
  58. cell.nameLabel.text = locations[indexPath.row].name
  59. cell.thumbnailImageView.image = UIImage(named: locations[indexPath.row].image)
  60. cell.locationLabel.text = locations[indexPath.row].location
  61. cell.typeLabel.text = locations[indexPath.row].type
  62. cell.accessoryType = locations[indexPath.row].isVisited ? .checkmark : .none
  63. return cell
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement