0

I have a view with @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> for a custom dismiss action based on a published value around some logic like this:

.onAppear(perform: {
            viewModel.cancellable = viewModel.$shouldPopBack.sink(receiveValue: { shouldPopBackToHome in
                if shouldPopBackToHome {
                    presentationMode.wrappedValue.dismiss()
                }
            })
        })

This view also has another option to present a sheet

Button(action: {
            shouldNavigateToQRCodeScanner = true
        }, label: {
            Text("Scan QR code")
                .padding(.horizontal)
        }).sheet(isPresented: $shouldNavigateToQRCodeScanner, content: {
            QRCodeScannerView()
        })

The problem here is when I have @Environment(\.presentationMode) the QRCodeScannerView is been initialized twice, when I remove the presentationMode it works fine.


Update I've tried the same behaviour in a test project and it's the same

struct ContentView: View {

@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@State var isPresentd: Bool = false

var body: some View {
    NavigationView {
        Button(action: {
            isPresentd = true
        }, label: {
            Text("Navigate to Second View")
        })
        .sheet(isPresented: $isPresentd, content: {
                SecondView()
            })
    }
}

}
struct SecondView: View {

init() {
    print("Initialized")
}

var body: some View {
    Text("Second View")
}
}

It has the same issue

Screenshot

Hesham
  • 132
  • 2
  • 12
  • 2
    SwiftUI View is a value, it can be created many times by SwiftUI rendering engine, it is not under our control (in majority of cases). So just do not rely on that. – Asperi Mar 18 '21 at 11:56
  • The problem is it deinit the viewModel and it no longer holds any data – Hesham Mar 18 '21 at 16:20
  • Solved https://stackoverflow.com/a/61311279/506392 – nikans Jun 17 '22 at 04:19

0 Answers0