我正在尝试了解如何知道用户何时点击了使用.searchable修饰符的iOS应用程序中的搜索字段。苹果文档称,用户可以通过获取Environment值来了解用户何时与由searchable(text:placement:prompt:)等可搜索修饰符生成的搜索字段交互
然而,这第一个代码不起作用。文本总是说不搜索。我一定错过了一些基本的东西:
struct ContentView: View {
@Environment(\.isSearching) var isSearching
@State private var searchText: String = ""
var items = ["One", "Two", "Three", "Four", "Five"]
var body: some View {
NavigationStack {
VStack {
Text(isSearching ? "Searching" : "Not Searching")
List {
ForEach(searchResults, id: \.self) { item in
Text(item)
}
}
.listStyle(PlainListStyle())
.searchable(text: $searchText)
}//v
.padding()
}//nav
}//body
private var searchResults: [String] {
if searchText.isEmpty {
return items
} else {
return items.filter({ item in
item.contains(searchText)
})
}
}//var search results
}//struct
但是,如果我将大部分代码提取到另一个视图,这确实有效:
struct ContentView2: View {
@State private var searchText: String = ""
var body: some View {
NavigationStack {
SearchedView2 (searchText: $searchText)
.searchable(text: $searchText)
}//nav
}//body
}//struct
struct SearchedView2: View {
@Environment(\.isSearching) var isSearching
@Binding var searchText: String
var items = ["One", "Two", "Three", "Four", "Five"]
var body: some View {
VStack {
Text(isSearching ? "Searching" : "Not Searching")
List {
ForEach(searchResults, id: \.self) { item in
Text(item)
}
}
.listStyle(PlainListStyle())
}//v
.padding()
}//body
private var searchResults: [String] {
if searchText.isEmpty {
return items
} else {
return items.filter({ item in
item.contains(searchText)
})
}
}//var search results
}//struct
我很困惑。为什么第一段代码不起作用?欢迎提供指导。Xcode 14.0.1 iOS 16.0
1条答案
按热度按时间7kqas0il1#
让我们给予一下文档,
@Environment()
Package 器用给定的环境值\.isSearching
初始化,它表示在其中调用-SearchingExampl()
的上下文,然后尝试查找由.searchable()
修饰符创建的搜索字段,并提供其所有功能,包括isSearching
观察器。理论值:
https://developer.apple.com/documentation/swiftui/environment?language=swift
https://developer.apple.com/documentation/swiftui/environmentvalues
https://developer.apple.com/documentation/swiftui/environmentvalues/issearching
实践:
https://developer.apple.com/documentation/swiftui/adding-search-to-your-app