@Binding变量以每次一个字符发布字符串

huangapple go评论49阅读模式
英文:

@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)
}

huangapple
  • 本文由 发表于 2023年3月4日 05:39:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632110.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定