首页 > 解决方案 > 为什么在 SwiftUI 中,当使用 .sheet 呈现模态视图时,init() 被调用了两次

问题描述

我正在使用以下代码在 WatchOS 上产生这种情况

struct Modal : View {
    @Binding var showingModal : Bool
    
    init(showingModal : Binding<Bool>){
        self._showingModal = showingModal
        print("init modal")
    }
    
    var body: some View {
        Button(action: {
            self.showingModal.toggle()
        }, label: {
            Text("TTTT")
        })
    }
}

struct ContentView: View {
    @State var showingModal = false
    var body: some View {
        Button(action: {
            self.showingModal.toggle()
        }, label: {
            Text("AAAA")
        }).sheet(isPresented: $showingModal, content: {Modal(showingModal: self.$showingModal)})
    }
}

每次我按下主视图中的按钮以使用 .sheet 调用模态时,都会创建模态视图的两个实例。

有人可以解释这种现象吗?

标签: iosswiftiphoneswiftui

解决方案


我在我的代码中跟踪到在我的视图中有以下行:

@Environment(\.presentationMode) var presentation

由于https://stackoverflow.com/a/61311279/155186我一直在这样做,但由于某种原因,这个问题似乎对我来说已经消失了,所以我想我不再需要它了。

我已就此向 Apple 提交反馈 FB7723767。


推荐阅读