在SwiftUI中从子项的子项调用父项的函数

问题描述 投票:0回答:1

我具有将函数传递给ChildView的ParentView,然后在ChildView中单击按钮时在ParentView中调用该函数。但是,如果我希望孩子的孩子调用该函数该怎么办?我需要进一步传递该功能,还是有一种方法可以使该功能在整个环境中都可以访问?

struct ParentView: View {
    func parentFunction() {
        print("parentFunction called")
    }

    var body: some View {
        ChildView(p: parentFunction)
    }
}


struct ChildView: View {
    var p: () -> ()
    var body: some View {
        VStack {
            Text("child view")
            Button(action: {
                self.p()
            }) {
                Image(systemName: "person")
            }
        }
    }
}
swiftui
1个回答
0
投票

是,可以使用自定义定义的EnvironmentKey,然后使用它设置父视图环境功能,该功能将可用于所有子视图。

这里是方法演示

struct ParentFunctionKey: EnvironmentKey {
    static let defaultValue: (() -> Void)? = nil
}

extension EnvironmentValues {
    var parentFunction: (() -> Void)? {
        get { self[ParentFunctionKey.self] }
        set { self[ParentFunctionKey.self] = newValue }
    }
}

struct ParentView: View {
    func parentFunction() {
        print("parentFunction called")
    }

    var body: some View {
        VStack {
            ChildView()
        }
        .environment(\.parentFunction, parentFunction) // set in parent
    }
}

struct ChildView: View {
    @Environment(\.parentFunction) var parentFunction // join in child
    var body: some View {
        VStack {
            Text("child view")
            Button(action: {
                self.parentFunction?() // < use in child
            }) {
                Image(systemName: "person")
            }
            Divider()
            SubChildView()
        }
    }
}

struct SubChildView: View {
    @Environment(\.parentFunction) var parentFunction // join in next subchild
    var body: some View {
        VStack {
            Text("Subchild view")
            Button(action: {
                self.parentFunction?() // use in next subchild
            }) {
                Image(systemName: "person.2")
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.