我的问题:
我想在单击自定义 View 时调用函数
因此,我使用 @State 变量从自定义 View 中观察单击操作。但问题是我的值改变了但didSet函数没有触发
我的代码:
主要结构:
@State var buttonClicked : Bool = false {
didSet{
needToCallMyFunction() // not triggered
}
}
自定义结构:(对于我的自定义 View )
@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()
}
关于ios - Swift - didSet 属性未从绑定(bind)更改中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65389566/