Created
August 5, 2021 19:37
-
-
Save oliverfoggin/1fe01c3455614b79d2226295e5520157 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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