我提出了一个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")
})
}
}
}
为此,我只想在用户点击回车时启动网络访问。因此,我将onCommit
零件添加到SearchBarView
,并且didPressReturn()
仅在点击return时才调用该函数。到现在为止还挺好。
我不明白的是SearchDatabaseView
其中包含的内容SearchBarView
可以响应onCommit
并启动数据库searh-我该怎么做?
这是可能的方法
struct SearchBarView: View {
@Binding var text: String
var onCommit: () -> () = {} // inject callback
@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")
// do internal things...
self.onCommit() // << external callback
}
}
所以现在SearchDatabaseView
你可以
VStack {
SearchBarView(text: $searchText) {
// do needed things here ...
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句