Skip to content

Instantly share code, notes, and snippets.

@jayesh15111988
Created August 30, 2022 09:32
Show Gist options
  • Save jayesh15111988/6f05f5089d6e606214b9d676c1eefff0 to your computer and use it in GitHub Desktop.
Save jayesh15111988/6f05f5089d6e606214b9d676c1eefff0 to your computer and use it in GitHub Desktop.
A Source code to demonstrate new searchable modifier introduced in iOS 15
// Searchable.swift
import SwiftUI
struct Searchable: View {
@State var searchText: String = ""
private let suggestions = ["Milan", "Rome", "Paris", "Iceland", "Greenland", "Florida"]
//------------------------------------------------------------------------------------------------
@State private var showingAlert = false
//------------------------------------------------------------------------------------------------
var body: some View {
NavigationView {
SearchChildView(searchText: $searchText)
.searchable(text: $searchText) {
ForEach(suggestions, id: \.self) { suggestion in
HStack {
Image(systemName: "circle.fill")
Text(suggestion)
}
.searchCompletion(suggestion)
}
}
//--------------------------------------------------------------------------------------------
.onSubmit(of: .search, {
showingAlert = true
}).alert("Submitted search for \(searchText)", isPresented: $showingAlert) {
Button("OK", role: .cancel) {
// no-op
}
}
//---------------------------------------------------------------------------------------------
.navigationTitle("Search Experience")
}
}
}
struct Searchable_Previews: PreviewProvider {
static var previews: some View {
Searchable()
}
}
// SearchChildView.swift
import SwiftUI
struct SearchChildView: View {
@Binding var searchText: String
private let recentSearches: [String] = ["Boston", "Utah", "Bangalore", "Chennai"]
@Environment(\.isSearching)
private var isSearching: Bool
let places = [
Place(id: "1", name: "Mumbai", imageName: "car"),
Place(id: "2", name: "Vienna", imageName: "airplane"),
Place(id: "3", name: "Amsterdam", imageName: "camera"),
Place(id: "4", name: "Prague", imageName: "alarm"),
Place(id: "5", name: "Delhi", imageName: "bag")
]
var body: some View {
List {
Text("Search Text is \(searchText)")
ForEach(searchResults) { searchResult in
HStack {
Image(systemName: searchResult.imageName)
Text(searchResult.name)
}
}
}
.overlay(content: {
if isSearching && searchText.isEmpty {
List {
Text("Recent Searches")
.fontWeight(.heavy)
ForEach(recentSearches, id: \.self) { recentSearch in
Text(recentSearch)
}
}
}
})
}
var searchResults: [Place] {
if searchText.isEmpty {
return places
} else {
return places.filter { $0.name.contains(searchText) }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment