【发布时间】:2020-08-10 12:00:11
【问题描述】:
我制作了一个SearchBarView 视图以在各种其他视图中使用(为了清楚起见,我删除了所有布局修饰符,例如颜色和填充):
struct SearchBarView: View {
@Binding var text: String
@State private var isEditing = false
var body: some View {
HStack {
TextField("Search…", text: $text, onCommit: didPressReturn)
.overlay(
HStack {
Image(systemName: "magnifyingglass")
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
if isEditing {
Button(action: {
self.text = ""
}) {
Image(systemName: "multiply.circle.fill")
}
}
}
)
}
func didPressReturn() {
print("did press return")
}
}
在List 中过滤数据看起来很棒。
但现在我想使用SearchBarView 来搜索外部数据库。
struct SearchDatabaseView: View {
@Binding var isPresented: Bool
@State var searchText: String = ""
var body: some View {
NavigationView {
VStack {
SearchBarView(text: $searchText)
// need something here to respond to onCommit and initiate a network call.
}
.navigationBarTitle("Search...")
.navigationBarItems(trailing:
Button(action: { self.isPresented = false }) {
Text("Done")
})
}
}
}
为此,我只想在用户点击返回时开始网络访问。所以我在SearchBarView中添加了onCommit部分,而didPressReturn()函数确实只有在点击return时才会调用。到目前为止,一切顺利。
我不明白的是,包含 SearchBarView 的 SearchDatabaseView 如何响应 onCommit 并启动数据库搜索 - 我该怎么做?
【问题讨论】: