您可以在 Swift/SwiftUI 中的自定义结构初始值设定项中访问 @Environment 值吗?

Can you access @Environment values in a custom struct initializer in Swift/SwiftUI?

我一直在尝试根据 . Seems as though 实现自定义后退按钮,如何关闭 NavigationLink 是通过访问 @Environment 值 presentationMode 通过:

@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

然后在自定义按钮结构中调用 dismiss 方法:

var btnBack : some View { Button(action: {
        self.presentationMode.wrappedValue.dismiss()
        }) {
            HStack {
            Image("ic_back") // set image here
                .aspectRatio(contentMode: .fit)
                .foregroundColor(.white)
                Text("Go back")
            }
        }
    }

是否可以在结构的自定义初始化程序中访问 presentationMode 变量?我试过类似的东西:

init(var: Variable) {
        self.presentationMode = @Environment(\.presentationMode)
        self.var = var
}

或:

var presentationMode: Binding<PresentationMode>

init(var: Variable) {
        presentationMode = @Environment(\.presentationMode)
        self.var = var
} 

或(根据 Apple Docs 取消操作):

init(var: Variable) {
        @Environment(\.dismiss) var dismiss
        self.var = var
}

上面似乎初始化了,但在范围内找不到 dismiss。 iOS/Swift 的新手,不确定是否可行,但感谢您的指导!

答案是否定的,您不能在初始化程序中访问环境,但这不是必需的。您可以访问环境值而无需将它们分配给您的视图结构。

struct ButtonBack: View {
    @Environment(\.presentationMode) private var presentationMode

    var body: some View {
        Button(action: self.dismiss) {
            // some View
        }
    }

    private func dismiss() {
        self.presentationMode.wrappedValue.dismiss()
    }
}