I'm creating a project using SwiftUI and would like to add a search bar to the navigation bar like what exists in the native settings app, mail app, etc.
I've tried a few things, but can't quite get it to work. The following code runs fine, but the search bar won't show up (I've tried scrolling up) even if I include navigationController.navigationItem.hidesSearchBarWhenScrolling = false. Any help would be appreciated.
//
// ContentView.swift
// SwiftUITest
//
// Created by me on 1/7/20.
// Copyright © 2020 me. All rights reserved.
//
import SwiftUI
struct HomeView: View {
var body: some View {
ScrollView {
HStack {
Spacer(minLength: 0)
Text("Hello World")
Spacer(minLength: 0)
}
}
.navigationBarTitle(Text("Search"))
}
}
struct SecondView: View {
var body: some View {
return Text("Second View")
}
}
struct CustomUIViewControllerRepresentation: UIViewControllerRepresentable {
typealias UIViewControllerType = UINavigationController
func makeUIViewController(context: Context) -> UINavigationController {
let viewController = UIHostingController(rootView: HomeView())
let navigationController = UINavigationController(rootViewController: viewController)
navigationController.navigationBar.prefersLargeTitles = true
let searchController = UISearchController()
navigationController.navigationItem.searchController = searchController
return navigationController
}
func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {
}
}
struct ContentView: View {
var body: some View {
CustomUIViewControllerRepresentation()
}
}
(EDIT) iOS 15:
iOS 15 added the new property .searchable(). You should probably use that instead.
Original:
If anyone is still looking, I made a package to deal with this, since all the other solutions I found had some problem or other.
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)
}
}
}
try this:
-> this line was missing: viewController.navigationItem.searchController = searchController
func makeUIViewController(context: Context) -> UINavigationController {
let viewController = UIHostingController(rootView: HomeView())
let navigationController = UINavigationController(rootViewController: viewController)
navigationController.navigationBar.prefersLargeTitles = true
let searchController = UISearchController()
navigationController.navigationItem.searchController = searchController
viewController.navigationItem.searchController = searchController
return navigationController
}
Related
Is it possible to add a view modifier inside .onChange?
Simplified example:
content
.onChange(of: publishedValue) {
content.foregroundColor(.red)
}
I have a theme that when changed needs to change the status bar color. I have a view modifier created for that ( https://barstool.engineering/set-the-ios-status-bar-style-in-swiftui-using-a-custom-view-modifier/ ). The modifier works fine, but I need to update it as the publishedValue changes.
Actual minimal example:
import SwiftUI
struct ContentView: View {
#ObservedObject var viewModel: TestViewModel
var body: some View {
ZStack {
Rectangle().foregroundColor(.mint)
VStack(alignment: .center, spacing: 25) {
Text("Test text \(viewModel.publishedValue)")
.onChange(of: viewModel.publishedValue) { newValue in
// Change status bar color
if viewModel.publishedValue % 2 == 0 {
self.body.statusBarStyle(.lightContent)
} else {
self.body.statusBarStyle(.darkContent)
}
}
Button("Increment") {
viewModel.publishedValue += 1
}
}
}
.ignoresSafeArea()
.statusBarStyle(.lightContent)
}
}
class TestViewModel: ObservableObject {
#Published var publishedValue: Int
init(publishedValue: Int) {
self.publishedValue = publishedValue
}
}
extension View {
/// Overrides the default status bar style with the given `UIStatusBarStyle`.
///
/// - Parameters:
/// - style: The `UIStatusBarStyle` to be used.
func statusBarStyle(_ style: UIStatusBarStyle) -> some View {
return self.background(HostingWindowFinder(callback: { window in
guard let rootViewController = window?.rootViewController else { return }
let hostingController = HostingViewController(rootViewController: rootViewController, style: style)
window?.rootViewController = hostingController
}))
}
}
fileprivate class HostingViewController: UIViewController {
private var rootViewController: UIViewController?
private var style: UIStatusBarStyle = .default
init(rootViewController: UIViewController, style: UIStatusBarStyle) {
self.rootViewController = rootViewController
self.style = style
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func viewDidLoad() {
super.viewDidLoad()
guard let child = rootViewController else { return }
addChild(child)
view.addSubview(child.view)
child.didMove(toParent: self)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return style
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
setNeedsStatusBarAppearanceUpdate()
}
}
fileprivate struct HostingWindowFinder: UIViewRepresentable {
var callback: (UIWindow?) -> ()
func makeUIView(context: Context) -> UIView {
let view = UIView()
DispatchQueue.main.async { [weak view] in
self.callback(view?.window)
}
return view
}
func updateUIView(_ uiView: UIView, context: Context) {
// ...
}
}
GitHub repo for the example project: https://github.com/Iikeli/view-modifier-test
You are way overcomplicating this. Since your viewModel is #ObservedObject and the publishedValue is Published, the body of your View will be recalculated automatically every time publishedValue is updated. There's no need for a manual onChange.
You can simply move the logic into the input argument of statusBarStyle.
var body: some View {
ZStack {
Rectangle().foregroundColor(.mint)
VStack(alignment: .center, spacing: 25) {
Text("Test text \(viewModel.publishedValue)")
Button("Increment") {
viewModel.publishedValue += 1
}
}
}
.ignoresSafeArea()
.statusBarStyle(viewModel.publishedValue % 2 == 0 ? .lightContent : .darkContent)
}
Or even better, move the logic into a separate computed property:
var body: some View {
....
.statusBarStyle(statusBarStyle)
}
private var statusBarStyle: UIStatusBarStyle {
viewModel.publishedValue % 2 == 0 ? .lightContent : .darkContent
}
The short answer is no, but that doesn't mean you can't use it to have views change based on some .onChange(..) action. For example.
#State var somethingChanged = false
Text(somethingChanged ? "First Value" : "Second Value")
// Your code/view
.onChange(..) {
//Some Condition or whatever you want.
somethingChanged = true
}
Your usage might look something like this.
content
.foregroundColor(somethingChanged ? .red : .blue)
.onChange(ofPublishedValue) {
somethingChanged = true
}
First of all, thanks for the help. Neither of the answers helped in my situation, since I couldn't get the modifier to update with the variable change. But with some Googling and trying out different solutions I figured out a working solution for updating the status bar colors.
I needed to update the style variable in the HostingViewController, and then update accordingly. So I added the HostingViewController as a #StateObject and updated the style variable inside the .onChange(). Not quite the solution I was going with to start out, but it does work.
The code:
import SwiftUI
import Introspect
struct ContentView: View {
#ObservedObject var viewModel: TestViewModel
#StateObject var hostingViewController: HostingViewController = .init(rootViewController: nil, style: .default)
var body: some View {
ZStack {
Rectangle().foregroundColor(.mint)
VStack(alignment: .center, spacing: 25) {
Text("Test text \(viewModel.publishedValue)")
.onChange(of: viewModel.publishedValue) { newValue in
// Change status bar color
if viewModel.publishedValue % 2 == 0 {
hostingViewController.style = .lightContent
} else {
hostingViewController.style = .darkContent
}
}
Button("Increment") {
viewModel.publishedValue += 1
}
}
}
.ignoresSafeArea()
.introspectViewController { viewController in
let window = viewController.view.window
guard let rootViewController = window?.rootViewController else { return }
hostingViewController.rootViewController = rootViewController
window?.rootViewController = hostingViewController
}
}
}
class TestViewModel: ObservableObject {
#Published var publishedValue: Int
init(publishedValue: Int) {
self.publishedValue = publishedValue
}
}
class HostingViewController: UIViewController, ObservableObject {
var rootViewController: UIViewController?
var style: UIStatusBarStyle = .default {
didSet {
self.rootViewController?.setNeedsStatusBarAppearanceUpdate()
}
}
init(rootViewController: UIViewController?, style: UIStatusBarStyle) {
self.rootViewController = rootViewController
self.style = style
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func viewDidLoad() {
super.viewDidLoad()
guard let child = rootViewController else { return }
addChild(child)
view.addSubview(child.view)
child.didMove(toParent: self)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return style
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
setNeedsStatusBarAppearanceUpdate()
}
}
Big shoutout to this answer for giving me all that I needed to implement the solution. Note: You can override the rootViewController however you like, I used SwiftUI-Introspect as we are already using it in our project anyway.
GitHub branch
How can I control the preferred presentation size of a modal sheet on iPad with SwiftUI? I'm surprised how hard it is to find an answer on Google for this.
Also, what is the best way to know if the modal is dismissed by dragging it down (cancelled) or actually performing a custom positive action?
Here is my solution for showing a form sheet on an iPad in SwiftUI:
struct MyView: View {
#State var show = false
var body: some View {
Button("Open Sheet") { self.show = true }
.formSheet(isPresented: $show) {
Text("Form Sheet Content")
}
}
}
Enabled by this UIViewControllerRepresentable
class FormSheetWrapper<Content: View>: UIViewController, UIPopoverPresentationControllerDelegate {
var content: () -> Content
var onDismiss: (() -> Void)?
private var hostVC: UIHostingController<Content>?
required init?(coder: NSCoder) { fatalError("") }
init(content: #escaping () -> Content) {
self.content = content
super.init(nibName: nil, bundle: nil)
}
func show() {
guard hostVC == nil else { return }
let vc = UIHostingController(rootView: content())
vc.view.sizeToFit()
vc.preferredContentSize = vc.view.bounds.size
vc.modalPresentationStyle = .formSheet
vc.presentationController?.delegate = self
hostVC = vc
self.present(vc, animated: true, completion: nil)
}
func hide() {
guard let vc = self.hostVC, !vc.isBeingDismissed else { return }
dismiss(animated: true, completion: nil)
hostVC = nil
}
func presentationControllerWillDismiss(_ presentationController: UIPresentationController) {
hostVC = nil
self.onDismiss?()
}
}
struct FormSheet<Content: View> : UIViewControllerRepresentable {
#Binding var show: Bool
let content: () -> Content
func makeUIViewController(context: UIViewControllerRepresentableContext<FormSheet<Content>>) -> FormSheetWrapper<Content> {
let vc = FormSheetWrapper(content: content)
vc.onDismiss = { self.show = false }
return vc
}
func updateUIViewController(_ uiViewController: FormSheetWrapper<Content>,
context: UIViewControllerRepresentableContext<FormSheet<Content>>) {
if show {
uiViewController.show()
}
else {
uiViewController.hide()
}
}
}
extension View {
public func formSheet<Content: View>(isPresented: Binding<Bool>,
#ViewBuilder content: #escaping () -> Content) -> some View {
self.background(FormSheet(show: isPresented,
content: content))
}
}
You should be able to modify the code in func show() according to UIKit specs in order to get the sizing the way you like (and you can even go so far as to inject parameters from the SwiftUI side if needed). This is just how I get a form sheet to work on iPad as .sheet was just too big for my use case
I just posted the same in this SO How can I make a background color with opacity on a Sheet view?
but it seems to do exactly what I need it to do. It makes the background of the sheet transparent while allowing the content to be sized as needed to appear as if it's the only part of the sheet. Works great on the iPad.
Using the AWESOME answer from #Asperi that I have been trying to find all day, I have built a simple view modifier that can now be applied inside a .sheet or .fullScreenCover modal view and provides a transparent background. You can then set the frame modifier for the content as needed to fit the screen without the user having to know the modal is not custom sized.
import SwiftUI
struct ClearBackgroundView: UIViewRepresentable {
func makeUIView(context: Context) -> some UIView {
let view = UIView()
DispatchQueue.main.async {
view.superview?.superview?.backgroundColor = .clear
}
return view
}
func updateUIView(_ uiView: UIViewType, context: Context) {
}
}
struct ClearBackgroundViewModifier: ViewModifier {
func body(content: Content) -> some View {
content
.background(ClearBackgroundView())
}
}
extension View {
func clearModalBackground()->some View {
self.modifier(ClearBackgroundViewModifier())
}
}
Usage:
.sheet(isPresented: $isPresented) {
ContentToDisplay()
.frame(width: 300, height: 400)
.clearModalBackground()
}
In case it helps anyone else, I was able to get this working by leaning on this code to hold the view controller:
https://gist.github.com/timothycosta/a43dfe25f1d8a37c71341a1ebaf82213
struct ViewControllerHolder {
weak var value: UIViewController?
init(_ value: UIViewController?) {
self.value = value
}
}
struct ViewControllerKey: EnvironmentKey {
static var defaultValue: ViewControllerHolder? { ViewControllerHolder(UIApplication.shared.windows.first?.rootViewController) }
}
extension EnvironmentValues {
var viewController: ViewControllerHolder? {
get { self[ViewControllerKey.self] }
set { self[ViewControllerKey.self] = newValue }
}
}
extension UIViewController {
func present<Content: View>(
presentationStyle: UIModalPresentationStyle = .automatic,
transitionStyle _: UIModalTransitionStyle = .coverVertical,
animated: Bool = true,
completion: #escaping () -> Void = { /* nothing by default*/ },
#ViewBuilder builder: () -> Content
) {
let toPresent = UIHostingController(rootView: AnyView(EmptyView()))
toPresent.modalPresentationStyle = presentationStyle
toPresent.rootView = AnyView(
builder()
.environment(\.viewController, ViewControllerHolder(toPresent))
)
if presentationStyle == .overCurrentContext {
toPresent.view.backgroundColor = .clear
}
present(toPresent, animated: animated, completion: completion)
}
}
Coupled with a specialized view to handle common elements in the modal:
struct ModalContentView<Content>: View where Content: View {
// Use this function to provide the content to display and to bring up the modal.
// Currently only the 'formSheet' style has been tested but it should work with any
// modal presentation style from UIKit.
public static func present(_ content: Content, style: UIModalPresentationStyle = .formSheet) {
let modal = ModalContentView(content: content)
// Present ourselves
modal.viewController?.present(presentationStyle: style) {
modal.body
}
}
// Grab the view controller out of the environment.
#Environment(\.viewController) private var viewControllerHolder: ViewControllerHolder?
private var viewController: UIViewController? {
viewControllerHolder?.value
}
// The content to be displayed in the view.
private var content: Content
public var body: some View {
VStack {
/// Some specialized controls, like X button to close omitted...
self.content
}
}
Finally, simply call:
ModalContentView.present( MyAwesomeView() )
to display MyAwesomeView inside of a .formSheet modal.
There are some issues in #ccwasden's answer. Dismissing popover won't change $isPresented all the time, as delegate is not set and hostVC is never assigned.
Here are some modifications required.
In FlexSheetWrapper:
func show() {
guard hostVC == nil else { return }
let vc = UIHostingController(rootView: content())
vc.view.sizeToFit()
vc.preferredContentSize = vc.view.bounds.size
vc.modalPresentationStyle = .formSheet
vc.presentationController?.delegate = self
hostVC = vc
self.present(vc, animated: true, completion: nil)
}
And in FormSheet:
func updateUIViewController(_ uiViewController: FlexSheetWrapper<Content>,
context: UIViewControllerRepresentableContext<FlexSheet<Content>>) {
if show {
uiViewController.show()
}
else {
uiViewController.hide()
}
}
From #ccwasden answer, I fixed the problem when you $isPresented = true at the beginning of code, the modal will not present when the view is loaded, To do so here is code View+FormSheet.swift
Result
// You can now set `test = true` at first
.formSheet(isPresented: $test) {
Text("Hi")
}
View+FormSheet.swift
import SwiftUI
class ModalUIHostingController<Content>: UIHostingController<Content>, UIPopoverPresentationControllerDelegate where Content : View {
var onDismiss: (() -> Void)
required init?(coder: NSCoder) { fatalError("") }
init(onDismiss: #escaping () -> Void, rootView: Content) {
self.onDismiss = onDismiss
super.init(rootView: rootView)
view.sizeToFit()
preferredContentSize = view.bounds.size
modalPresentationStyle = .formSheet
presentationController?.delegate = self
}
func presentationControllerWillDismiss(_ presentationController: UIPresentationController) {
print("modal dismiss")
onDismiss()
}
}
class ModalUIViewController<Content: View>: UIViewController {
var isPresented: Bool
var content: () -> Content
var onDismiss: (() -> Void)
private var hostVC: ModalUIHostingController<Content>
private var isViewDidAppear = false
required init?(coder: NSCoder) { fatalError("") }
init(isPresented: Bool = false, onDismiss: #escaping () -> Void, content: #escaping () -> Content) {
self.isPresented = isPresented
self.onDismiss = onDismiss
self.content = content
self.hostVC = ModalUIHostingController(onDismiss: onDismiss, rootView: content())
super.init(nibName: nil, bundle: nil)
}
func show() {
guard isViewDidAppear else { return }
self.hostVC = ModalUIHostingController(onDismiss: onDismiss, rootView: content())
present(hostVC, animated: true)
}
func hide() {
guard !hostVC.isBeingDismissed else { return }
dismiss(animated: true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
isViewDidAppear = true
if isPresented {
show()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
isViewDidAppear = false
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
show()
}
}
struct FormSheet<Content: View> : UIViewControllerRepresentable {
#Binding var show: Bool
let content: () -> Content
func makeUIViewController(context: UIViewControllerRepresentableContext<FormSheet<Content>>) -> ModalUIViewController<Content> {
let onDismiss = {
self.show = false
}
let vc = ModalUIViewController(isPresented: show, onDismiss: onDismiss, content: content)
return vc
}
func updateUIViewController(_ uiViewController: ModalUIViewController<Content>,
context: UIViewControllerRepresentableContext<FormSheet<Content>>) {
if show {
uiViewController.show()
}
else {
uiViewController.hide()
}
}
}
extension View {
public func formSheet<Content: View>(isPresented: Binding<Bool>,
#ViewBuilder content: #escaping () -> Content) -> some View {
self.background(FormSheet(show: isPresented,
content: content))
}
}
I am trying to use a Share function inside my MacOS app in SwiftUI. I am having a URL to a file, which I want to share. It can be images/ documents and much more.
I found NSSharingServicePicker for MacOS and would like to use it. However, I am struggeling to use it in SwiftUI.
Following the documentation, I am creating it like this:
let shareItems = [...]
let sharingPicker : NSSharingServicePicker = NSSharingServicePicker.init(items: shareItems as [Any])
sharingPicker.show(relativeTo: NSZeroRect, of:shareView, preferredEdge: .minY)
My problem is in that show() method. I need to set a NSRect, where I can use NSZeroRect.. but I am struggeling with of: parameter. It requires a NSView. How can I convert my current view as NSView and use it that way. Or can I use my Button as NSView(). I am struggling with that approach.
Another option would be to use a NSViewRepresentable. But should I just create a NSView and use it for that method.
Here is minimal working demo example
struct SharingsPicker: NSViewRepresentable {
#Binding var isPresented: Bool
var sharingItems: [Any] = []
func makeNSView(context: Context) -> NSView {
let view = NSView()
return view
}
func updateNSView(_ nsView: NSView, context: Context) {
if isPresented {
let picker = NSSharingServicePicker(items: sharingItems)
picker.delegate = context.coordinator
// !! MUST BE CALLED IN ASYNC, otherwise blocks update
DispatchQueue.main.async {
picker.show(relativeTo: .zero, of: nsView, preferredEdge: .minY)
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator(owner: self)
}
class Coordinator: NSObject, NSSharingServicePickerDelegate {
let owner: SharingsPicker
init(owner: SharingsPicker) {
self.owner = owner
}
func sharingServicePicker(_ sharingServicePicker: NSSharingServicePicker, didChoose service: NSSharingService?) {
// do here whatever more needed here with selected service
sharingServicePicker.delegate = nil // << cleanup
self.owner.isPresented = false // << dismiss
}
}
}
Demo of usage:
struct TestSharingService: View {
#State private var showPicker = false
var body: some View {
Button("Share") {
self.showPicker = true
}
.background(SharingsPicker(isPresented: $showPicker, sharingItems: ["Message"]))
}
}
Another option without using NSViewRepresentable is:
extension NSSharingService {
static func submenu(text: String) -> some View {
return Menu(
content: {
ForEach(items, id: \.title) { item in
Button(action: { item.perform(withItems: [text]) }) {
Image(nsImage: item.image)
Text(item.title)
}
}
},
label: {
Image(systemName: "square.and.arrow.up")
}
)
}
}
You lose things like the "more" menu item or recent recipients. But in my opinion it's more than enough, simple and pure SwiftUI.
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:
(EDIT) iOS 15:
iOS 15 added the new property .searchable(). You should probably use that instead.
Original:
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.
UISearchController works when attached to a List. It becomes buggy when you use something other like a ScrollView or VStack. I have reported this in Apple's Feedback app and I hope others will do the same.
Never the less if you like to include a UISearchController in your App. I created a Swift Package at Github named NavigationSearchBar.
Code
// Copyright © 2020 Mark van Wijnen
// 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
public extension View {
func navigationSearchBar(text: Binding<String>, scopeSelection: Binding<Int> = Binding.constant(0), options: [NavigationSearchBarOptionKey : Any] = [NavigationSearchBarOptionKey : Any](), actions: [NavigationSearchBarActionKey : NavigationSearchBarActionTask] = [NavigationSearchBarActionKey : NavigationSearchBarActionTask]()) -> some View {
overlay(NavigationSearchBar<AnyView>(text: text, scopeSelection: scopeSelection, options: options, actions: actions).frame(width: 0, height: 0))
}
func navigationSearchBar<SearchResultsContent>(text: Binding<String>, scopeSelection: Binding<Int> = Binding.constant(0), options: [NavigationSearchBarOptionKey : Any] = [NavigationSearchBarOptionKey : Any](), actions: [NavigationSearchBarActionKey : NavigationSearchBarActionTask] = [NavigationSearchBarActionKey : NavigationSearchBarActionTask](), #ViewBuilder searchResultsContent: #escaping () -> SearchResultsContent) -> some View where SearchResultsContent : View {
overlay(NavigationSearchBar<SearchResultsContent>(text: text, scopeSelection: scopeSelection, options: options, actions: actions, searchResultsContent: searchResultsContent).frame(width: 0, height: 0))
}
}
public struct NavigationSearchBarOptionKey: Hashable, Equatable, RawRepresentable {
public static let automaticallyShowsSearchBar = NavigationSearchBarOptionKey("automaticallyShowsSearchBar")
public static let obscuresBackgroundDuringPresentation = NavigationSearchBarOptionKey("obscuresBackgroundDuringPresentation")
public static let hidesNavigationBarDuringPresentation = NavigationSearchBarOptionKey("hidesNavigationBarDuringPresentation")
public static let hidesSearchBarWhenScrolling = NavigationSearchBarOptionKey("hidesSearchBarWhenScrolling")
public static let placeholder = NavigationSearchBarOptionKey("Placeholder")
public static let showsBookmarkButton = NavigationSearchBarOptionKey("showsBookmarkButton")
public static let scopeButtonTitles = NavigationSearchBarOptionKey("scopeButtonTitles")
public static func == (lhs: NavigationSearchBarOptionKey, rhs: NavigationSearchBarOptionKey) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init(_ rawValue: String) {
self.init(rawValue: rawValue)
}
}
public struct NavigationSearchBarActionKey: Hashable, Equatable, RawRepresentable {
public static let onCancelButtonClicked = NavigationSearchBarActionKey("onCancelButtonClicked")
public static let onSearchButtonClicked = NavigationSearchBarActionKey("onSearchButtonClicked")
public static let onBookmarkButtonClicked = NavigationSearchBarActionKey("onBookmarkButtonClicked")
public static func == (lhs: NavigationSearchBarActionKey, rhs: NavigationSearchBarActionKey) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init(_ rawValue: String) {
self.init(rawValue: rawValue)
}
}
public typealias NavigationSearchBarActionTask = () -> Void
fileprivate struct NavigationSearchBar<SearchResultsContent>: UIViewControllerRepresentable where SearchResultsContent : View {
typealias UIViewControllerType = Wrapper
typealias OptionKey = NavigationSearchBarOptionKey
typealias ActionKey = NavigationSearchBarActionKey
typealias ActionTask = NavigationSearchBarActionTask
#Binding var text: String
#Binding var scopeSelection: Int
let options: [OptionKey : Any]
let actions: [ActionKey : ActionTask]
let searchResultsContent: () -> SearchResultsContent?
init(text: Binding<String>, scopeSelection: Binding<Int> = Binding.constant(0), options: [OptionKey : Any] = [OptionKey : Any](), actions: [ActionKey : ActionTask] = [ActionKey : ActionTask](), #ViewBuilder searchResultsContent: #escaping () -> SearchResultsContent? = { nil }) {
self._text = text
self._scopeSelection = scopeSelection
self.options = options
self.actions = actions
self.searchResultsContent = searchResultsContent
}
func makeCoordinator() -> Coordinator {
Coordinator(representable: self)
}
func makeUIViewController(context: Context) -> Wrapper {
Wrapper()
}
func updateUIViewController(_ wrapper: Wrapper, context: Context) {
if wrapper.searchController != context.coordinator.searchController {
wrapper.searchController = context.coordinator.searchController
}
if let hidesSearchBarWhenScrolling = options[.hidesSearchBarWhenScrolling] as? Bool {
wrapper.hidesSearchBarWhenScrolling = hidesSearchBarWhenScrolling
}
if options[.automaticallyShowsSearchBar] as? Bool == nil || options[.automaticallyShowsSearchBar] as! Bool {
wrapper.navigationBarSizeToFit()
}
if let searchController = wrapper.searchController {
searchController.automaticallyShowsScopeBar = true
if let obscuresBackgroundDuringPresentation = options[.obscuresBackgroundDuringPresentation] as? Bool {
searchController.obscuresBackgroundDuringPresentation = obscuresBackgroundDuringPresentation
} else {
searchController.obscuresBackgroundDuringPresentation = false
}
if let hidesNavigationBarDuringPresentation = options[.hidesNavigationBarDuringPresentation] as? Bool {
searchController.hidesNavigationBarDuringPresentation = hidesNavigationBarDuringPresentation
}
if let searchResultsContent = searchResultsContent() {
(searchController.searchResultsController as? UIHostingController<SearchResultsContent>)?.rootView = searchResultsContent
}
}
if let searchBar = wrapper.searchController?.searchBar {
searchBar.text = text
if let placeholder = options[.placeholder] as? String {
searchBar.placeholder = placeholder
}
if let showsBookmarkButton = options[.showsBookmarkButton] as? Bool {
searchBar.showsBookmarkButton = showsBookmarkButton
}
if let scopeButtonTitles = options[.scopeButtonTitles] as? [String] {
searchBar.scopeButtonTitles = scopeButtonTitles
}
searchBar.selectedScopeButtonIndex = scopeSelection
}
}
class Coordinator: NSObject, UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate {
let representable: NavigationSearchBar
let searchController: UISearchController
init(representable: NavigationSearchBar) {
self.representable = representable
var searchResultsController: UIViewController? = nil
if let searchResultsContent = representable.searchResultsContent() {
searchResultsController = UIHostingController<SearchResultsContent>(rootView: searchResultsContent)
}
self.searchController = UISearchController(searchResultsController: searchResultsController)
super.init()
self.searchController.searchResultsUpdater = self
self.searchController.searchBar.delegate = self
}
// MARK: - UISearchResultsUpdating
func updateSearchResults(for searchController: UISearchController) {
guard let text = searchController.searchBar.text else { return }
DispatchQueue.main.async { [weak self] in self?.representable.text = text }
}
// MARK: - UISearchBarDelegate
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
guard let action = self.representable.actions[.onCancelButtonClicked] else { return }
DispatchQueue.main.async { action() }
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
guard let action = self.representable.actions[.onSearchButtonClicked] else { return }
DispatchQueue.main.async { action() }
}
func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
guard let action = self.representable.actions[.onBookmarkButtonClicked] else { return }
DispatchQueue.main.async { action() }
}
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
DispatchQueue.main.async { [weak self] in self?.representable.scopeSelection = selectedScope }
}
}
class Wrapper: UIViewController {
var searchController: UISearchController? {
get {
self.parent?.navigationItem.searchController
}
set {
self.parent?.navigationItem.searchController = newValue
}
}
var hidesSearchBarWhenScrolling: Bool {
get {
self.parent?.navigationItem.hidesSearchBarWhenScrolling ?? true
}
set {
self.parent?.navigationItem.hidesSearchBarWhenScrolling = newValue
}
}
func navigationBarSizeToFit() {
self.parent?.navigationController?.navigationBar.sizeToFit()
}
}
}
Usage
import SwiftUI
import NavigationSearchBar
struct ContentView: View {
#State var text: String = ""
#State var scopeSelection: Int = 0
var body: some View {
NavigationView {
List {
ForEach(1..<5) { index in
Text("Sample Text")
}
}
.navigationTitle("Navigation")
.navigationSearchBar(text: $text,
scopeSelection: $scopeSelection,
options: [
.automaticallyShowsSearchBar: true,
.obscuresBackgroundDuringPresentation: true,
.hidesNavigationBarDuringPresentation: true,
.hidesSearchBarWhenScrolling: false,
.placeholder: "Search",
.showsBookmarkButton: true,
.scopeButtonTitles: ["All", "Missed", "Other"]
],
actions: [
.onCancelButtonClicked: {
print("Cancel")
},
.onSearchButtonClicked: {
print("Search")
},
.onBookmarkButtonClicked: {
print("Present Bookmarks")
}
], searchResultsContent: {
Text("Search Results for \(text) in \(String(scopeSelection))")
})
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I tried making UISearchController work with NavigationView and UIViewRepresentable to inject the search controller but the result was really buggy. Probably the best way to do it is to use a regular UINavigationController instead of NavigationView and then also use a container UIViewController where you set navigationItem.searchController to your UISearchController.
I have UISearchController that's been made UIViewControllerRepresentable for SwiftUI, as follows:
struct SearchViewController<Content: View>: UIViewControllerRepresentable {
var content: () -> Content
let searchResultsView = SearchResultsView()
init(#ViewBuilder content: #escaping () -> Content) {
self.content = content
}
func makeUIViewController(context: Context) -> UINavigationController {
let rootViewController = UIHostingController(rootView: content())
let navigationController = UINavigationController(rootViewController: rootViewController)
let searchResultsController = UIHostingController(rootView: searchResultsView)
// Set nav properties
navigationController.navigationBar.prefersLargeTitles = true
navigationController.definesPresentationContext = true
// Create search controller
let searchController = UISearchController(searchResultsController: searchResultsController)
searchController.searchBar.autocapitalizationType = .none
searchController.delegate = context.coordinator
searchController.searchBar.delegate = context.coordinator // Monitor when the search button is tapped.
// Create default view
rootViewController.navigationItem.searchController = searchController
rootViewController.title = "Search"
return navigationController
}
func updateUIViewController(_ navigationController: UINavigationController, context: UIViewControllerRepresentableContext<SearchViewController>) {
//
}
}
This works, and displays the searchResultsController when the user is searching. However, the searchResultsController doesn't seem to know it's navigational context/stack, so I can't navigate from that list view in the searchResultsController.
Can this be structured to allow navigation from searchResultsController, or is this currently a SwiftUI limitation.
Any advice is much appreciated!
I recently also need to implement this feature(search bar like navigation bar) in my app. Looking you snippets really inspired m2! My Thanks First!
After learning from you, ula1990, Lorenzo Boaro and V8tr, I implemented my own.
I set the searchResultsController to nil (due to untappable navigation link in it, so i set it to nil).
Demo
Code:
struct SearchController<Result: View>: UIViewControllerRepresentable {
#Binding var searchText: String
private var content: (_ searchText:String)->Result
private var searchBarPlaceholder: String
init(_ searchBarPlaceholder: String = "", searchedText: Binding<String>,
resultView: #escaping (_ searchText:String) -> Result) {
self.content = resultView
self._searchText = searchedText
self.searchBarPlaceholder = searchBarPlaceholder
}
func makeUIViewController(context: Context) -> UINavigationController {
let contentViewController = UIHostingController(rootView: SearchResultView(result: $searchText, content: content))
let navigationController = UINavigationController(rootViewController: contentViewController)
let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = context.coordinator
searchController.obscuresBackgroundDuringPresentation = false // for results
searchController.searchBar.placeholder = searchBarPlaceholder
contentViewController.title = "\\(Title)" // for customization
contentViewController.navigationItem.searchController = searchController
contentViewController.navigationItem.hidesSearchBarWhenScrolling = true
contentViewController.definesPresentationContext = true
searchController.searchBar.delegate = context.coordinator
return navigationController
}
func updateUIViewController(_ uiViewController: UINavigationController, context: UIViewControllerRepresentableContext<SearchController>) {
//
}
}
extension SearchController {
func makeCoordinator() -> SearchController<Result>.Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UISearchResultsUpdating, UISearchBarDelegate {
var parent: SearchController
init(_ parent: SearchController){self.parent = parent}
// MARK: - UISearchResultsUpdating
func updateSearchResults(for searchController: UISearchController) {
self.parent.searchText = searchController.searchBar.text!
}
// MARK: - UISearchBarDelegate
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.parent.searchText = ""
}
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
self.parent.searchText = ""
return true
}
}
}
// "nofity" the result content about the searchText
struct SearchResultView<Content: View>: View {
#Binding var searchText: String
private var content: (_ searchText:String)->Content
init(result searchText: Binding<String>, #ViewBuilder content: #escaping (_ searchText:String) -> Content) {
self._searchText = searchText
self.content = content
}
var body: some View {
content(searchText)
}
}
I don't if this is what you want, but thanks again!.
(EDIT) iOS 15:
iOS 15 added the new property .searchable(). You should probably use that instead.
Original:
I just made a package that would likely solve this issue. It's similar to #EthanMengoreo's answer, but has (in my opinion) a more SwiftUI-like syntax.
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)
}
}
}