SwiftUI:在环境中存储关闭? [英] SwiftUI: store closure in environment?

查看:23
本文介绍了SwiftUI:在环境中存储关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望给定视图的子视图能够调用在父视图上定义的公共闭包.

I would like child views of a given view to be able to call a common closure defined on the parent.

所以父视图会有一个闭包:

So the parent view would have a closure:

var testClosure:(()->())?

有没有一种方法可以让闭包在整个视图层次结构中可用,而不必通过链中的每个视图向下传递?

Is there a way to make that closure available throughout the view hierarchy without having to pass it down through each view down the chain?

推荐答案

您可以使用 EnvironmentKey/EnvironmentValue 声明并使用 .environment:

You can declare it with EnvironmentKey/EnvironmentValue and pass it through using .environment:

typealias MyClosure = (() -> ())?

private struct ClosureKey: EnvironmentKey {
    static let defaultValue : MyClosure = { }
}

extension EnvironmentValues {
    var myClosure : MyClosure {
        get { self[ClosureKey.self] }
        set { self[ClosureKey.self] = newValue }
    }
}

struct ContentView : View {
    @Environment(\.myClosure) var closure
    
    var testClosure : MyClosure = {
        print("Here")
    }
    
    var body: some View {
        ChildView()
            .environment(\.myClosure, testClosure)
    }
}

struct ChildView : View {
    @Environment(\.myClosure) var closure
    
    var body: some View {
        Text("Hello, world")
            .onAppear {
                closure?()
            }
    }
}

这篇关于SwiftUI:在环境中存储关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆