我有一个主视图A。有时,我会覆盖一个导航视图B并调用视图C。在呈现视图C时,我想在视图A中调用一个函数以更新视图A的呈现。
我尝试在栈溢出found here.上由另一个人实现该解决方案,我正在使用SwiftUI在Xcode 12中构建它。
下面是我解决问题的尝试,
struct Parent: View {
var body: some View {
Text("Hello World!")
}.environment(\.parentFunction, moveCards)
func moveCards() {
//Change I want to happen
}
}
struct ParentFunctionKey: EnvironmentKey {
static let defaultValue: (() -> Void)? = nil
}
extension EnvironmentValues {
var ParentFunction: (() -> Void)? {
get { self[ParentFunctionKey.self] }
set { self[ParentFunctionKey.self] = newValue }
}
}
struct GrandchildView: View {
@Environment(\.parentFunction) var moveCards
var body: some View {
Button(action: {
self.moveCards?()
}){
Text("Submit")
}
}
}