![](/img/trans.png)
[英]Why is didSet called twice on the TextField binding in SwiftUI?
[英]Facing with some strange behaviour of State or Binding in didSet situation in SwiftUI
I am updating my State variable with a Binding from another View, I have some code in didSet of my State, it would fired when I do set value from State, but not from Binding, for this reason I have to give a didSet to Binding這個 State,這對我來說不合邏輯,綁定應該綁定,但它使用更新 State 的優勢創建了該值的自己版本,我在徘徊,如果它是一個錯誤,或者它應該以這種方式,我的意思是我我期待在狀態綁定方面的引用類型行為,但是使用這個向下代碼? 它顯示更像值類型! 為什么會這樣? 我期待 State 的 didSet 即使來自 Binding 的更新也會被解雇!
import SwiftUI
struct ContentView: View {
@State var someProperty: String = "Empty string!" {
didSet(oldValue) {
print("State didSet → " + someProperty)
}
}
var body: some View {
Text(someProperty)
.padding()
ButtonView(someProperty: $someProperty)
}
}
struct ButtonView: View {
@Binding var someProperty: String {
didSet(oldValue) {
print("Binding didSet → " + someProperty)
}
}
var body: some View {
Button("update Text") { someProperty = "Hello, world!" }
}
}
更新:
struct ContentView: View {
@State private var someProperty: String = "Empty string!" {
didSet(oldValue) {
print("State didSet → " + someProperty)
}
}
var body: some View {
Text(someProperty)
.padding()
Button("update Text") { someProperty = "Hello, world!" }
}
}
使用自定義綁定
var body: some View {
Text(someProperty)
.padding()
ButtonView(someProperty: Binding(
get: { self.someProperty },
set: { self.someProperty = $0 }
))
}
didSet
僅在您直接修改@State
而不是在您更改其內部值時才與@State
一起使用。
請注意, State
是一個包裝器。 如果您使用Binding
更改其內部值(此處_someProperty
),則不會調用didSet
。
您可以使用onReceive
或onChange
代替:
import Combine
import SwiftUI
struct ContentView: View {
@State private var someProperty: String = "Empty string!"
var body: some View {
Text(someProperty)
.padding()
// updated on changes only
.onChange(of: someProperty) {
print("State onChange → " + $0)
}
// updated every time
.onReceive(Just(someProperty)) {
print("State onReceive → " + $0)
}
ButtonView(someProperty: $someProperty)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.