Newbie Questions
Newbie Questions

Reputation: 463

Be able to search by Subtitle

i set up the search so i could search by the title of my annotation but i want to search by the subtitle as well !

Code:

func updateSearchResults(for searchController: UISearchController) {
    
    matchingItems = []
    guard let mapView = mapView,
        let searchBarText = searchController.searchBar.text else { return }
    
    for item in self.mapView!.annotations    {
        let title = item.title!!
        
        
        if title.hasPrefix(searchBarText) && searchBarText != ""
        {
            matchingItems.append(item)
            
     }
    self.tableView.reloadData()
}

How can i implement it here in the code i have right now?

Thanks for your Help!

Upvotes: 1

Views: 88

Answers (1)

pableiros
pableiros

Reputation: 16052

You can do something like this to search by subtitle too:

func updateSearchResults(for searchController: UISearchController) {

    guard let mapView = mapView,
        let searchBarText = searchController.searchBar.text else { return  }

    matchingItems = self.mapView!.annotations.filter { annotation -> Bool in
        if annotation.title!.range(of: searchBarText, options: .caseInsensitive) != nil {
            return true
        }

        if annotation.subtitle!.range(of: searchBarText, options: .caseInsensitive) != nil {
            return true
        }

        return false
    }

   self.tableView.reloadData()
}

Upvotes: 2

Related Questions