简体   繁体   English

为什么在 SwiftUI 中,当用 .sheet 呈现模态视图时,init() 被调用两次

[英]Why is it in SwiftUI, when presenting modal view with .sheet, init() is called twice

I am producing the situation on WatchOS with the following code我正在使用以下代码在 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)})
    }
}

Every time I press the button in the master view to summon the modal with .sheet, Two instances of the modal view are created.每次我按下主视图中的按钮以使用 .sheet 调用模态时,都会创建模态视图的两个实例。

Could someone explain this phenomenon?有人可以解释这种现象吗?

I tracked this down in my code to having the following line in my View:我在我的代码中跟踪到在我的视图中有以下行:

@Environment(\.presentationMode) var presentation

I had been doing it due to https://stackoverflow.com/a/61311279/155186 , but for some reason that problem seems to have disappeared for me so I guess I no longer need it.由于https://stackoverflow.com/a/61311279/155186 ,我一直在这样做,但由于某种原因,这个问题似乎对我来说已经消失了,所以我想我不再需要它了。

I've filed Feedback FB7723767 with Apple about this.我已就此向 Apple 提交了反馈 FB7723767。

It is probably a bug, as of Xcode 11.4.1 (11E503a).从 Xcode 11.4.1 (11E503a) 开始,这可能是一个错误。 Beware, that if for example initializing view models (or anything else for that matter) like so:请注意,例如,如果像这样初始化视图模型(或其他任何事情):

.sheet(isPresented: $isEditingModalPresented) {
    LEditView(vm: LEditViewModel(), isPresented: self.$isEditingModalPresented)
}

the VM will be initialized twice. VM 将被初始化两次。

Comment out/remove the init() method from Modal with everything else the same.从 Modal 注释掉/删除 init() 方法,其他所有内容都相同。 You should be able to solve the issue of two instances of Modal being created, its because you are explicitly initializing the binding (showingModal) in the init() of Modal.您应该能够解决创建两个 Modal 实例的问题,这是因为您在 Modal 的 init() 中显式初始化了绑定(showingModal)。 Hope this makes sense.希望这是有道理的。

private let uniqueId: String = "uniqueId" 

Button(action: {
    self.showingModal.toggle()
}, label: {
    Text("AAAA")
})
    .sheet(isPresented: $showingModal) {
        Modal(showingModal: self.$showingModal)
          .id("some-unique-id")
    }

Ex:前任:

.id(self.uniqueId) .id(self.uniqueId)

Add unique id to your .sheet and not't worry :)将唯一 ID 添加到您的 .sheet 中,不用担心:)

But, do not use UUID(), because sheet view will be represented on every touch event

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM