Search code examples
iosswiftstructenvironmentinit

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


I've been trying to implement a custom back button according to this posting. Seems as though most common response in how to dismiss a NavigationLink is through accessing the @Environment value presentationMode through:

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

And then calling dismiss Method in a custom button struct:

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")
            }
        }
    }

Is it possible to access the presentationMode var in a custom initializer in a struct? I've tried things like:

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

or:

var presentationMode: Binding<PresentationMode>

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

or (with dismiss action per Apple Docs):

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

The above seems to initialize, but can't find dismiss in scope. New to iOS/Swift & not sure this is possible, but appreciate any guidance!


Solution

  • The answer is no, you can't access the environment in the initializer, but that's not necessary. You can access the environment values without assigning them to your View struct.

    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()
        }
    }