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.

2

There are 2 best solutions below

3
On BEST ANSWER

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)
    }
}

Results: Search Bar is present

2
On

(EDIT) iOS 15+:

iOS 15 added the new property .searchable() (here is the official guide on how to use it). You should use it instead unless you still need to target iOS 14 or below.

Original:

If anyone is still looking, I just made a package to deal with this really cleanly, inspired by @arsenius's answer

I'm also including the full relevant source code for v1.0.0 here for those who dislike links or just want to copy/paste (I am not keeping this in sync with any updates to the GitHub repo).

Extension:

// Copyright © 2020 thislooksfun
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the “Software”), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import SwiftUI
import Combine

public extension View {
    public func navigationBarSearch(_ searchText: Binding<String>) -> some View {
        return overlay(SearchBar(text: searchText).frame(width: 0, height: 0))
    }
}

fileprivate struct SearchBar: UIViewControllerRepresentable {
    @Binding
    var text: String
    
    init(text: Binding<String>) {
        self._text = text
    }
    
    func makeUIViewController(context: Context) -> SearchBarWrapperController {
        return SearchBarWrapperController()
    }
    
    func updateUIViewController(_ controller: SearchBarWrapperController, context: Context) {
        controller.searchController = context.coordinator.searchController
    }
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(text: $text)
    }
    
    class Coordinator: NSObject, UISearchResultsUpdating {
        @Binding
        var text: String
        let searchController: UISearchController
        
        private var subscription: AnyCancellable?
        
        init(text: Binding<String>) {
            self._text = text
            self.searchController = UISearchController(searchResultsController: nil)
            
            super.init()
            
            searchController.searchResultsUpdater = self
            searchController.hidesNavigationBarDuringPresentation = true
            searchController.obscuresBackgroundDuringPresentation = false
            
            self.searchController.searchBar.text = self.text
            self.subscription = self.text.publisher.sink { _ in
                self.searchController.searchBar.text = self.text
            }
        }
        
        deinit {
            self.subscription?.cancel()
        }
        
        func updateSearchResults(for searchController: UISearchController) {
            guard let text = searchController.searchBar.text else { return }
            self.text = text
        }
    }
    
    class SearchBarWrapperController: UIViewController {
        var searchController: UISearchController? {
            didSet {
                self.parent?.navigationItem.searchController = searchController
            }
        }
        
        override func viewWillAppear(_ animated: Bool) {
            self.parent?.navigationItem.searchController = searchController
        }
        override func viewDidAppear(_ animated: Bool) {
            self.parent?.navigationItem.searchController = searchController
        }
    }
}

Usage:

import SwiftlySearch

struct MRE: View {
  let items: [String]

  @State
  var searchText = ""

  var body: some View {
    NavigationView {
      List(items.filter { $0.localizedStandardContains(searchText) }) { item in
        Text(item)
      }.navigationBarSearch(self.$searchText)
    }
  }
}