SwiftUI View属性willSet& didSet属性观察器不起作用 [英] SwiftUI View Property willSet & didSet property observers not working
问题描述
我有一个带有附加ViewModel的SwiftUI(测试版5)视图.我想通过navigationLink导航到它并传递一个简单的参数(在本例中为FSAC)
I have a SwiftUI (Beta 5) view with an attached ViewModel. I want to navigate to it via a navigationLink and pass in a simple parameter (called FSAC in this case)
我使用
NavigationLink("Next", destination: MyTestView(FSAC: "testFsac"))
该视图具有一个带有willSet和didSet属性观察器的FSAC属性
The view has an FSAC Property with willSet and didSet property observer
struct MyTestView: View {
@ObservedObject var vm = MyTestViewModel()
var FSAC: String {
willSet {
print("will set fsac")
}
didSet {
print("did set fsac")
vm.FSAC = FSAC
}
}
var body: some View {
VStack {
Text("FSAC: \(FSAC)")
Text("VM FSAC: \(vm.FSAC)")
}
}
}
从不调用print语句.第一个文本框正确显示参数;第二个是空白.
The print statements are never called. The first text box displays the parameter correctly; the second is blank.
如何触发财产观察员?
更一般地说,是否存在使用NavigationLink将参数传递给具有ViewModel的View的正确"方法?
More generally, is there a "correct" way to use a navigationLink to pass parameters to a View that has a ViewModel?
推荐答案
感谢arsenius对为何财产观察员在这种情况下未触发的解释.
Thanks to arsenius for an explanation as to why the Property Observers did not fire in this instance.
作为修复,我删除了视图中的属性,并使用带有签名的init函数替换了该属性,该签名包含要从NavigationLink调用传递的必需数据.在初始化过程中,我直接在ViewModel上调用了一个函数.
As a fix, I removed the property in the view, and replaced it with an init function with a signature which included the required data to be passed from the NavigationLink call. Within the init, I called a function on the ViewModel directly.
struct MyTestView: View {
@ObservedObject var vm = MyTestViewModel()
init(FSAC: String) {
if(FSAC != "") {
vm.SetFsac(FSAC: FSAC)
}
}
...
这篇关于SwiftUI View属性willSet& didSet属性观察器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!