Skip to content

Instantly share code, notes, and snippets.

@ericlewis
Created August 30, 2019 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericlewis/73a3ef5ac1199a139d6b1e805df90889 to your computer and use it in GitHub Desktop.
Save ericlewis/73a3ef5ac1199a139d6b1e805df90889 to your computer and use it in GitHub Desktop.
import SwiftUI
struct SearchNavigationView<Content: View>: UIViewControllerRepresentable {
@Binding var searchText: String
@Binding var scope: Int
var showScope: Bool = false
var content: () -> Content
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> UINavigationController {
UINavigationController(rootViewController: UIHostingController(rootView: content()))
}
func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {
guard uiViewController.topViewController?.navigationItem.searchController == nil else {
return
}
let search = UISearchController(searchResultsController: nil)
search.searchResultsUpdater = context.coordinator
search.obscuresBackgroundDuringPresentation = false
if showScope {
search.automaticallyShowsScopeBar = true
search.searchBar.showsScopeBar = true
search.searchBar.delegate = context.coordinator
search.searchBar.scopeButtonTitles = ["Your Library", "All"]
}
uiViewController.topViewController?.navigationItem.searchController = search
uiViewController.topViewController?.navigationItem.hidesSearchBarWhenScrolling = false
}
class Coordinator: NSObject, UISearchResultsUpdating, UISearchBarDelegate {
var parent: SearchNavigationView
init(_ parent: SearchNavigationView) {
self.parent = parent
}
func updateSearchResults(for searchController: UISearchController) {
parent.searchText = searchController.searchBar.text ?? ""
}
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
parent.scope = selectedScope
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment