ios – How to implement a search function with SwiftUI


I have a question about a search function, especially how to get the word to search on one view and to display the result on another sheet with swift. If the search bar and the place to display the result are the same, the search function works well, so I feel like viewModel.listings cannot be updated properly with updateListingsForLocation(). That would be appreciated if you could help.
Search Results
Search Bar

# A View with a Search bar

@ObservedObject var viewModel = SearchedWordsObject(service: ExploreService())

TextField("Search words", text: $viewModel.searchWord)

.onChange(of: viewModel.searchWord) {
    if viewModel.searchWord.isEmpty {
          searchWord = false
          viewModel.updateListingsForLocation()
} }
.onSubmit {
      viewModel.updateListingsForLocation()
      searchWord = true
      showCreateView = true }
.sheet(isPresented: $showCreateView) {
SearchView(lookForWord : $searchWord)
}

# Sheet
@StateObject var viewModel = SearchedWordsObject(service: ExploreService())
@Binding var lookForWord : Bool

if lookForWord {
        LazyVStack(spacing: 10) {
           ForEach(viewModel.listings) { listing in
                  HStack {
                     Text("\(listing.wordID)")
                     Text("\(listing.word) : \(listing.meaning1)")

# Data 
class SearchedWordsObject : ObservableObject {
    @Published var listings = [Word] ()
    @Published var searchWord = ""
    private var listingsCopy = [Word]()
    private let service : ExploreService

 func updateListingsForLocation() {
        if searchWord.isEmpty {  self.listings = self.listingsCopy } 
        else {
         let filteredListings = listings.filter({
             $0.word.lowercased() == searchWord.lowercased()})
            self.listings = filteredListings
        }}}

I followed the youtube tutorial

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img