Created
August 30, 2019 16:16
-
-
Save ericlewis/73a3ef5ac1199a139d6b1e805df90889 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 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