I have a SearchController that conforms to UIViewControllerRepresentable, and I've implemented the required protocol methods. But when I created an instance of the SearchController in a SwiftUI struct, the SearchController doesn't appear on the screen once it's loaded. Does anyone have any suggestions on how I could integrate a UISearchController with SwiftUI? Thank you!
Here's the SearchController Struct that conforms to UIViewControllerRepresentable:
struct SearchController: UIViewControllerRepresentable {
let placeholder: String
@Binding var text: String
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
func makeUIViewController(context: Context) -> UISearchController {
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = context.coordinator
controller.obscuresBackgroundDuringPresentation = false
controller.hidesNavigationBarDuringPresentation = false
controller.searchBar.delegate = context.coordinator
controller.searchBar.placeholder = placeholder
return controller
}
func updateUIViewController(_ uiViewController: UISearchController, context: Context) {
uiViewController.searchBar.text = text
}
class Coordinator: NSObject, UISearchResultsUpdating, UISearchBarDelegate {
var controller: SearchController
init(_ controller: SearchController) {
self.controller = controller
}
func updateSearchResults(for searchController: UISearchController) {
let searchBar = searchController.searchBar
controller.text = searchBar.text!
}
}
}
Here is the code for my SwiftUIView that should display the SearchController:
struct SearchCarsView: View {
let cars = cardsData
// MARK: @State Properties
@State private var searchCarsText: String = ""
// MARK: Views
var body: some View {
SearchController(placeholder: "Name, Model, Year", text: $searchCarsText)
.background(Color.blue)
}
}
Here's an image of the SearchController not appearing on the screen:
iOS 15 added the new property .searchable()
. You should probably use that instead.
If anyone is still looking, I made a package to deal with this.
I'm also including the full relevant source code here for those who dislike links or just want to copy/paste.
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)
}
}
}
You can use UISearchController
directly once you resolved a reference to the underlying UIKit.UINavigationItem
of the actual SwiftUI View
. I made a writeup about the entire process with sample project at SwiftUI Search Bar in the Navigation Bar, but let me give you a quick overview below.
You can actually resolve the underlying UIViewController
of any SwiftUI View
leveraging on the fact that SwiftUI preserves the hierarchy of the view controllers (via children
and parent
references). Once you have the UIViewController
, you can set a UISearchController
to navigationItem.searchController
. If you extract the search controller instance to a distinct ObservableObject
, you can hook up the updateSearchResults(for:)
delegate method to a @Published
String
property, so you can make bindings on the SwiftUI side using @ObservedObject
.
Actually visual element in this case is UISearchBar
, so simplest start point should be as follows
import SwiftUI
import UIKit
struct SearchView: UIViewRepresentable {
let controller = UISearchController()
func makeUIView(context: UIViewRepresentableContext<SearchView>) -> UISearchBar {
self.controller.searchBar
}
func updateUIView(_ uiView: UISearchBar, context: UIViewRepresentableContext<SearchView>) {
}
typealias UIViewType = UISearchBar
}
struct TestSearchController: View {
var body: some View {
SearchView()
}
}
struct TestSearchController_Previews: PreviewProvider {
static var previews: some View {
TestSearchController()
}
}
everything next can be configured in init and coordinator made as delegate, as usual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With