Skip to content

Instantly share code, notes, and snippets.

@oliverfoggin
Created August 5, 2021 19:37
Show Gist options
  • Save oliverfoggin/1fe01c3455614b79d2226295e5520157 to your computer and use it in GitHub Desktop.
Save oliverfoggin/1fe01c3455614b79d2226295e5520157 to your computer and use it in GitHub Desktop.
import Foundation
import SwiftUI
class SearchableViewModel: ObservableObject {
let names = ["Oliver", "Emily", "Jessica", "Daniel", "Eva"]
@Published var searchText: String = ""
var searchResults: [String] {
if searchText.isEmpty {
return names
} else {
return names.filter { $0.lowercased().contains(searchText.lowercased()) }
}
}
var isSearching = false
var sectionTitle: String {
isSearching ? "Searching" : "Not Searching"
}
}
struct VMSearchableView: View {
@ObservedObject var viewModel: SearchableViewModel
var body: some View {
NavigationView {
VMSearchableList(viewModel: viewModel)
.navigationBarTitle("Searchable")
.searchable(
text: $viewModel.searchText,
prompt: "Search names..."
)
}
}
}
struct VMSearchableList: View {
@ObservedObject var viewModel: SearchableViewModel
@Environment(\.isSearching) var isSearching
var body: some View {
List {
Section(viewModel.sectionTitle) {
ForEach(viewModel.searchResults, id: \.self) { name in
Text(name)
}
}
}
.navigationBarTitle("Searchable")
.onChange(of: isSearching) { newValue in
viewModel.isSearching = newValue
}
}
}
struct VMSearchableView_Previews: PreviewProvider {
static var previews: some View {
VMSearchableView(viewModel: .init())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment