Home > Enterprise >  No idea how to hide List under Searchbar
No idea how to hide List under Searchbar

Time:09-27

A simple search form (like movies etc), there is some information in the database, I did a live search, but for some reason the List argument displays all the values ​​​​from the database under the search form before I start typing in search form, but the results should be displayed at the moment when I type key letters or the words HEEELP!

ContentView:

import SwiftUI
import Firebase
 
struct ContentView: View {
     
    @State var search = ""
     
    @ObservedObject var data = getData()
     
    var body: some View {
        
        NavigationView{
            List {
                ForEach(self.data.datas.filter {(self.search.isEmpty ? true : $0.title.localizedCaseInsensitiveContains(self.search))}, id: \.id) { rs in
                     
                    NavigationLink(destination: Detail(data: rs)) {
                        Text(rs.title)
                    }
                }
            }
            .navigationBarTitle("Search item")
            .searchable(text: self.$search)
 
        }
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
 
 
struct Detail : View {
     
    var data : dataType
     
    var body : some View{
        VStack {
            Text(data.title)
                .font(.title)
                .fontWeight(.bold)
            Text(data.description)
        }.padding()
    }
}

CodePudding user response:

you could try this example code, it will not display anything until you type something in the search bar. It also takes into account the "HEEELP".

struct ContentView: View {
    @State var search = ""
    @StateObject var data = getData() // <-- here

    // -- here, replace `DataType` with your type of `data.datas`
    var searchResults: [DataType] {
        if search == "HEEELP" {
            return data.datas  // return everything
        } else {
            return search.isEmpty
            ? []  // return nothing
            : data.datas.filter{$0.title.localizedCaseInsensitiveContains(search)} // filtered
        }
    }

   var body: some View {
       NavigationView{
           List {
               ForEach(searchResults, id: \.id) { rs in   // <-- here
                   NavigationLink(destination: Detail(data: rs)) {
                       Text(rs.title)
                   }
               }
           }
           .navigationBarTitle("Search item")
           .searchable(text: self.$search)
       }
   }
}
  • Related