SwiftUI 具有 @Environment(\.presentationMode) 用于消除视图行为不当

问题描述

我有一个带有 @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> 的视图,用于基于已发布的值进行自定义关闭操作,如下所示:

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

此视图还有另一个选项可以显示工作表

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

这里的问题是当我有 @Environment(\.presentationMode) 时,QRCodeScannerView 被初始化了两次,当我删除了presentationMode 时它工作正常。


更新 我在测试项目中尝试了相同的行为,结果相同

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

同样的问题

Screenshot

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)