I am trying to create a SwiftUI view where I have a NavigationView that wraps a custom MapView (which wraps MKMapView), but, with very minimal success, I cannot seem to integrate a search controller into the NavigationView, unlike how you would easily be able to with a UINavigationController. I have tried to create my own custom NavigationView with some success, but I don't particularly want to recreate something of that scope in order to add one piece of functionality (unless that's the only solution).
Realistically, I mainly want to know if it is even possible to do what I'm asking, or if that is something I would have to implement myself, and if so, how?
Thanks!
import SwiftUI
struct CustomNavigationController<Content: View>: UIViewControllerRepresentable {
var title: String
var content: () -> Content
init(title: String, @ViewBuilder content: @escaping () -> Content) {
self.content = content
self.title = title
}
func makeUIViewController(context: UIViewControllerRepresentableContext<CustomNavigationController<Content>>) -> UINavigationController {
let contents = UIHostingController(rootView: self.content())
let nc = UINavigationController(rootViewController: contents)
nc.navigationBar.prefersLargeTitles = true
return nc
}
func updateUIViewController(_ uiViewController: UINavigationController, context: UIViewControllerRepresentableContext<CustomNavigationController<Content>>) {
uiViewController.navigationBar.topItem?.title = title
let results = SearchResultsController()
let sc = UISearchController(searchResultsController: results)
sc.searchResultsUpdater = results
sc.hidesNavigationBarDuringPresentation = false
sc.obscuresBackgroundDuringPresentation = false
uiViewController.navigationBar.topItem?.searchController = sc
}
}
import UIKit
import MapKit
class SearchResultsController: UITableViewController {
let reuseIdentifier = "Cell"
var results: [MKMapItem] = []
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
let selected = results[indexPath.row].placemark
print(selected)
cell.textLabel?.text = selected.title
cell.detailTextLabel?.text = selected.title
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Clicked")
}
}
extension SearchResultsController : UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let searchBarText = searchController.searchBar.text else { return }
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = searchBarText
request.region = .init()
let search = MKLocalSearch(request: request)
search.start(completionHandler: { response, error in
guard let response = response else { return }
self.results = response.mapItems
self.tableView.reloadData()
})
}
}
That is the code for my custom UINavigationController to make something similar to a NavigationView. This works and displays the search bar in the navigation bar, but it isn't ideal nor do I feel like it is best practice.
I was able to get this working without using UINavigationController
in a UIViewControllerRepresentable
. In fact, in my own experiments in answering this question I found that to be a quite error prone method when views get updated.
The technique here is similar to that question: Use a dummy UIViewController
in order to configure your navigation.
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(destination: Text("Bye")) {
Text("Hi")
.background(SearchControllerSetup())
.navigationBarTitle("Hello", displayMode: .inline)
}
}
}
}
struct SearchControllerSetup: UIViewControllerRepresentable {
typealias UIViewControllerType = UIViewController
func makeCoordinator() -> SearchCoordinator {
return SearchCoordinator()
}
func makeUIViewController(context: Context) -> UIViewController {
return UIViewController()
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
// This will be called multiple times, including during the push of a new view controller
if let vc = uiViewController.parent {
vc.navigationItem.searchController = context.coordinator.search
}
}
}
class SearchCoordinator: NSObject {
let updater = SearchResultsUpdater()
lazy var search: UISearchController = {
let search = UISearchController(searchResultsController: nil)
search.searchResultsUpdater = self.updater
search.obscuresBackgroundDuringPresentation = false
search.searchBar.placeholder = "Type something"
return search
}()
}
class SearchResultsUpdater: NSObject, UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let text = searchController.searchBar.text else { return }
print(text)
}
}