There is now a native way to include a search bar in your SwiftUI apps.
Check out these sources:
- Apple Documentation - https://developer.apple.com/documentation/swiftui/form/searchable(text:placement:)
- Tutorial - https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-a-search-bar-to-filter-your-data
An extension to SwiftUI that will add the UISearchController.
Update your Package.swift
file:
let package = Package(
...,
dependencies: [
.package(
url: "https://github.com/markvanwijnen/NavigationSearchBar.git",
from: "1.3.0"),
...
],
...
)
- Go to File > Swift Packages > Add Package Depencency...
- Enter
https://github.com/markvanwijnen/NavigationSearchBar.git
as the URL - Select your desired versioning constraint
- Click Next
- Click Finish
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: {
NavigationLink(destination: Text("Destination")) {
Text("Search Results for \(text) in \(String(scopeSelection))")
}
})
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
If you have been enjoying my free Swift package, please consider showing your support by buying me a coffee through the link below. Thanks in advance!