【发布时间】:2021-06-13 06:09:25
【问题描述】:
我正在尝试 Apple WWDC21 上推出的 SwiftUI 3.0 的新功能。
我特别尝试使用.searchable 修饰符在列表中实现搜索栏,并让用户使用NavigationLink 从搜索结果导航到项目视图。
struct OrderItem : Identifiable {
let id = UUID()
var label : String
var value : Bool = false
}
struct BindingTest: View {
@State var items = [OrderItem(label: "Shirts"), OrderItem(label: "Pants"), OrderItem(label: "Socks")]
@State private var searchedText = ""
@ViewBuilder
var body: some View {
NavigationView {
List($items) { $item in
NavigationLink(destination: ItemView(item: $item)) {
HStack {
if(item.value) {
Image(systemName: "star.fill").foregroundColor(.yellow)
}
Text(item.label)
}
}
}.navigationBarTitle("Clothing")
// Search bar
.searchable(text: $searchedText, placement: .automatic) {
if searchedText != "" {
// Search result
ForEach($items.filter({$0.label.wrappedValue.contains(searchedText)})) { $item in
NavigationLink(destination: ItemView(item: $item)) {
HStack {
if(item.value) {
Image(systemName: "star.fill").foregroundColor(.yellow)
}
Text(item.label)
}
}.searchCompletion(item.label)
}
}
}
}
}
}
但是当我在搜索结果列表中并点击一个结果时,NavigationLink 不起作用,它会显示原始列表。还有其他人遇到这个问题吗?
[编辑]
我检查了这个NavigationLink inside .searchable does not work,但不幸的是它没有回答我的问题,因为我的NavigationLink 已经在NavigationView 中。
【问题讨论】:
-
不幸的是,正如您在我的代码中看到的那样,NavigationLink 已经在 NavigationView 中。
-
我也有同样的问题。一,我将多个过滤器应用于我的 ForEach。我的 ForEach 正在为我的数组中的每个项目呈现一个 NavigationLink。 NavigationLink 有一个目的地,我在其中传递一个 @State 变量。当我点击应用过滤器的下一个视图时,该视图只会将我送回主视图,而我无法访问子视图。如果我删除搜索和过滤器,那么导航层次结构的行为与我预期的一样。 Apple 的交付再次令人失望
标签: swift swiftui searchable