英文:
@Binding variable publishes String one character at a time
问题
我有一个带有`Binding`的视图,如下所示:
struct MyView: View {
@Binding var myString: String
var body: some View {
VStack {
// 不重要
}
.onReceive(myString.publisher) { receiveValue in
print(receiveValue)
}
}
}
还有一个父视图:
struct ParentView: View {
@State var myString: String
var body: some View {
Button("按钮") {
myString = "Foo"
}
MyView(myString: $myString)
}
}
思路是每当绑定的变量改变(在这种情况下是`myString`),接收器就会触发并打印新的字符串。这确实起作用,但发生了一些有趣的事情。每当点击按钮时,新字符串的每个字符都作为单独的事件发布:
F
o
o
如果将绑定的变量包装在`ObservedObject`中,就不会发生这种情况。如何让`myString.publisher`一次性发布整个字符串呢?
英文:
I have a View with a Binding
like this:
struct MyView: View {
@Binding var myString: String
var body: some View {
VStack {
// Not important
}
.onReceive(myString.publisher) { receiveValue in
print(receiveValue)
}
}
}
and a Parent View:
struct ParentView: View {
@State var myString: String
var body: some View {
Button("Button") {
myString = "Foo"
}
MyView(myString: myString)
}
}
The idea is that each time the bound variable changes myString
in this case, the receiver fires and prints the new string. And this does work, but something interesting happens. I get each character of the new string published as a separate event when the button is tapped:
F
o
o
If I wrap the bound variable in an ObservedObject
this does not happen. How can I get the myString.publisher
to publish the entire String at once?
答案1
得分: 2
使用 onChange(of:)
替代
.onChange(of: myString) { value in
print("onChange", value)
}
英文:
Use onChange(of:)
instead
.onChange(of: myString) { value in
print("onChange", value)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论