![](/img/trans.png)
[英]Swift didSet called but not updating UILabel - iOS Property observer
[英]Swift - didSet property not called from binding changes
我的问题:
当我的 customView 单击时,我想调用 function
所以我使用@State 变量从我的自定义视图中观察点击动作。 但问题是我的值改变了但没有触发 didSet function
我的代码:
主要结构:
@State var buttonClicked : Bool = false {
didSet{
needToCallMyFunction() // not triggered
}
}
自定义结构:(对于我的自定义视图)
@Binding var isClicked : Bool
someview
.onTapGesture(perform: {
print("custom clicked")
isClicked.toggle()
})
在主视图中使用.onChange(of:)
修饰符,例如
SomeView()
.onChange(of: buttonClicked) { _ in
self.needToCallMyFunction()
}
更新:SwiftUI 1.0 / iOS 13+ 的变体
import Combine // needed to use Just
...
SomeView()
.onReceive(Just(buttonClicked)) { _ in
self.needToCallMyFunction()
}
Asperi 解决方案工作正常。
但它在较低版本中有一个错误。 它调用了多次
我找到了另一个解决方案
SomeView(buttonClicked:
Binding(get: { self.buttonClicked },
set: { self.buttonClicked = $0
print("your action here ")
}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.