问题描述
我正在尝试通过位于我的 ContentView 结构中的 showPopup(v: AnyView)
方法更新名为 showPopup 的 @State 布尔值。
@State var popupShowing: Bool = false
设置 showPopup(v: AnyView)
布尔值的方法 popupShowing
也位于 ContentView
public func showPopup(v: AnyView) {
lightTap.impactOccurred()
popupController.set(v)
print("setting popupShowing to: true")
popupShowing = true // this is what should be updating the @State boolean
print("popupShowing = ",popupShowing)
}
奇怪的是,我有两个方法调用 showPopup 并传递 AnyView
的引用,其中只有一个没有设置 popupShowing
布尔值,另一个方法 {{1 }} 完全正常。 (两个方法也都位于ContentView中
这是调用 tappedAddCT
的错误方法,它不会导致 showPopup(v:Anyview)
变量发生变化
popupShowing
这里是另一种调用 /*
* When editing a CT we bring up the popup add CT view with the corresponding elements
*/
public func showCTPopupFor(id: UUID) {
let ct = cTypeHandler.getControllerFrom(id: id)!.ct
// this is the call to the method above,for some reason it does not set the @State popupShowing boolean
showPopup(v: AnyView(EditCubeTypeView(controller: ctEditController,contentView: self,setCT: ct)))
}
的方法,它出于某种原因允许 showPopup(v:Anyview)
实际设置 @State showPopup(v:Anyview)
布尔值
showingPopup
由于某种原因,上述方法对 public func tappedAddCT() {
print("creating new Type view")
showPopup(v: AnyView(NewCubeTypeView(controller: ctEditController,contentView: self)))
}
的调用有效。
以下是控制台输出,输出显示,事实上,popupShowing 变量仅通过 showPopup(...)
设置
这也是我从上面的 showCTPopupFor(id:UUID)
方法中的打印语句获得的输出
不需要的结果,仅在通过 showPopup(v:Anyview)
调用 showPopup(v:Anyview)
时发生
showCTPopupFor(id: UUID)
预期结果,仅在通过 setting popupShowing to: true
popupShowing = false
调用 showPopup(v:Anyview)
时发生
tappedAddCT()
起初这似乎是一个简单的问题,但我似乎无法弄清楚,是否有一些我完全忽略的@State SwiftUI 规则?
解决方法
在重新组织我的引用后,我发现 popupShowing 变量没有更新的原因是在某个时候,popupShowing 变量作为其子级的主 ContentView 被 swiftui 在后台自动销毁和重新创建。 我猜 swiftui 在认为结构旧或不需要时会使用结构执行此操作。
我通过创建一个单独的 ContentViewController 类作为 ContentVIew 的 @StateObject 来解决这个问题。 ContentViewController 是一个类而不是结构体,因此它在整个运行周期中保持不变。