Created
June 24, 2021 23:33
-
-
Save pcolton/5f94f8c12ebfcd01588ec3166fb82509 to your computer and use it in GitHub Desktop.
SwiftUI dismissSearch example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Created by Paul Colton on 6/24/21. | |
// | |
import SwiftUI | |
@main | |
struct DismissApp: App { | |
var body: some Scene { | |
WindowGroup { | |
ContentView() | |
} | |
} | |
} | |
extension String: Identifiable { | |
public var id: String { self } | |
} | |
struct ContentView: View { | |
@State var items: [String] = ["Paul", "John", "Joe", "Jenny", "Gill"] | |
@State private var searchText = "" | |
@State var item: String? = nil | |
var body: some View { | |
NavigationView { | |
List { | |
ForEach(filtered, id: \.self) { item in | |
Button { | |
self.item = item | |
} label: { | |
Text(item).font(.title3) | |
} | |
.padding() | |
} | |
.sheet(item: $item) { result in | |
NavigationView { | |
DetailView(item: result) | |
} | |
} | |
.navigationTitle("Top Names") | |
.searchable(text: $searchText, prompt: "Filter items") | |
} | |
} | |
} | |
var filtered: [String] { | |
guard searchText.isEmpty == false else { return items } | |
return items.filter { $0.contains(searchText) } | |
} | |
} | |
struct DetailView: View { | |
var item: String | |
@Environment(\.dismiss) private var dismiss | |
@Environment(\.dismissSearch) private var dismissSearch | |
var body: some View { | |
VStack { | |
Text("\(item)") | |
} | |
.toolbar { | |
Button("Close") { | |
dismiss() | |
dismissSearch() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment