我有一个简单的TextField可以像这样绑定到状态“位置”,
TextField("Search Location", text: $location)
我想在每次该字段更改时调用一个函数,如下所示:
TextField("Search Location", text: $location) {
self.autocomplete(location)
}
但是,这不起作用。我知道有回调,onEditingChanged-但是,这似乎只有在焦点集中时才会触发。
如何在每次更新字段时调用此函数?
答案 0 :(得分:15)
从iOS 14,macOS 11或任何其他包含SwiftUI 2.0的操作系统开始,有一个名为.onChange
的新修饰符,用于检测给定state
的任何更改:
struct ContentView: View {
@State var location: String = ""
var body: some View {
TextField("Your Location", text: $location)
.onChange(of: location) {
print($0) // You can do anything due to the change here.
// self.autocomplete($0) // like this
}
}
}
对于较旧的iOS和其他SwiftUI 1.0平台,您可以使用onReceive
:
.onReceive(location.publisher) {
print($0)
}
请注意,它返回的是更改,而不是整个值。如果您需要与onChange
相同的行为,则可以使用 combine 并遵循@ pawello2222提供的答案。
答案 1 :(得分:12)
您可以使用自定义闭包创建绑定,如下所示:
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)
}
}
}
答案 2 :(得分:10)
使用onReceive
:
import Combine
import SwiftUI
struct ContentView: View {
@State var location: String = ""
var body: some View {
TextField("Search Location", text: $location)
.onReceive(Just(location)) { location in
// print(location)
}
}
}
答案 3 :(得分:6)
如果需要使用ViewModel
,另一种解决方案可以是:
import SwiftUI
import Combine
class ViewModel: ObservableObject {
@Published var location = "" {
didSet {
print("set")
//do whatever you want
}
}
}
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
TextField("Search Location", text: $viewModel.location)
}
}
答案 4 :(得分:1)
我发现最有用的是TextField具有一个名为onEditingChanged的属性,该属性在编辑开始和编辑完成时被调用。
TextField("Enter song title", text: self.$userData.songs[self.songIndex].name, onEditingChanged: { (changed) in
if changed {
print("text edit has begun")
} else {
print("committed the change")
saveSongs(self.userData.songs)
}
}).textFieldStyle(RoundedBorderTextFieldStyle())
.font(.largeTitle)
答案 5 :(得分:1)
虽然其他答案可能有效,但这个答案对我有用,我需要倾听文本变化并对其做出反应。
第一步创建一个扩展函数。
extension Binding {
func onChange(_ handler: @escaping (Value) -> Void) -> Binding<Value> {
Binding(
get: { self.wrappedValue },
set: { newValue in
self.wrappedValue = newValue
handler(newValue)
}
)
}
}
现在对 TextField 中的绑定调用 change,如下所示。
TextField("hint", text: $text.onChange({ (value) in
//do something here
}))