'Make TextField autosearch when map is opening

I have a TextField at the top of my map in Xcode. The map is opening when you choose food, to find the nearest restaurant.

I want TextField to search for the String automatically without the user needing to press enter. (I have already made the String for the food item in the TextField automatic):

@State private var search: String = "Pizza"

For now, the user needs to press on the TextField, then press Enter to execute the search:

TextField("Search", text: $search, onEditingChanged: { _ in })

How can I make the TextField automatic enter/execute the search?



Solution 1:[1]

try the following...

struct ContentView: View 
{
let searchFiles = ["Pizza", "Apple", "Pie", "Orange"]
@State private var searchText = ""

var body: some View {
    NavigationView {
        List {
            ForEach(searchResults, id: \.self) { name in
                NavigationLink(destination: Text(name)){
                    Text(name)
                }
            }
        }
        .searchable(text: $searchText)
        .navigationTitle("Foodlist")
    }
}

var searchResults: [String]{
    if searchText.isEmpty {
        return names
    } else {
        return names.filter{ $0.contains(searchText)}}
    }
}

This should create a searchbar for you and is automatically updated when filling the searchbar with text

Solution 2:[2]

There's also this option:

TextField("Search",text: $search)
    .onChange(of: search) { value in
          searchQuery(searchTerm: value)  
     }

func searchQuery(searchTerm: String) {
    searchRequest.naturalLanguageQuery = searchTerm
     MKLocalSearch(request: searchRequest).start { [self] response, _ in
        guard let response = response else { return }
        searches = response.mapItems.compactMap { $0.placemark } 
       /* searches are values of the searchText that the user entered,
       you can display it on an overview or sheet over the view of the map
       and maybe the user can tap it to choose it and display annotation on map */

      /* I also think it's a good idea to prevent duplicate values since 
        the search result sometime makes them, so I just run it through a Set 
        and parse it back to an array like this: */
        searches = Array(Set(searches))
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Iskandir
Solution 2 Gal