本文介绍了如何在SwiftUI中检测TextField上的实时更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的TextField可以像这样绑定到状态位置",
I have a simple TextField that binds to the state 'location' like this,
TextField("Search Location", text: $location)
我想在每次该字段更改时调用一个函数,如下所示:
I want to call a function each time this field changes, something like this:
TextField("Search Location", text: $location) {
self.autocomplete(location)
}
但是,这不起作用.我知道有一些回调,onEditingChanged-但是,这似乎只有在焦点集中时才会触发.
However this doesn't work. I know that there are callbacks, onEditingChanged - however this only seems to be triggered when the field is focussed.
如何在每次更新字段时调用此函数?
How can I get this function to call each time the field is updated?
推荐答案
您可以使用自定义闭包创建绑定,如下所示:
You can create a binding with a custom closure, like this:
struct ContentView: View {
@State var location: String = ""
var body: some View {
let binding = Binding<String>(get: {
self.location
}, set: {
self.location = $0
// do whatever you want here
})
return VStack {
Text("Current location: \(location)")
TextField("Search Location", text: binding)
}
}
}
这篇关于如何在SwiftUI中检测TextField上的实时更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!