关闭模态视图时不调用 onDisappear

Jan*_*Jan 3 ios swiftui

我依靠 SwiftUI.onDisappear来执行一些逻辑,但是当用户使用滑动手势关闭模态呈现的视图时,它不会被调用。繁殖

  • 以模态方式呈现视图“ChildView 1”
  • 在此视图上,推送“ChildView 2”作为导航子项
  • 向下滑动以关闭模态视图。

未调用“ChildView 2”的 .onDisappear。

重现的示例代码

import SwiftUI

struct ContentView: View {
    @State var isShowingModal
    var body: some View {
        NavigationView {
            Button(action: {
                self.isShowingModal.toggle()
            }) {
                Text("Show Modal")
            }
        }
        .sheet(isPresented: $isShowingModal) {
            NavigationView {
                ChildView(title: 1)
            }
        }
    }
}

struct ChildView: View {
    let title: Int
    var body: some View {

        NavigationLink(destination: ChildView(title: title + 1)) {
            Text("Show Child")
        }
        .navigationBarTitle("View \(title)")


        .onAppear {
            print("onAppear ChildView \(self.title)")
        }
        .onDisappear {
            print("onDisappear ChildView \(self.title)")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

onAppear ChildView 1
onAppear ChildView 2
onDisappear ChildView 1
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

小智 6

如果您正在寻找在实际模态被解除时发生的逻辑,您将要在此处调用它,在那里我打印出 Modal Dismissed:

struct ContentView: View {
    @State var isShowingModal = false
    var body: some View {
        NavigationView {
            Button(action: {
                self.isShowingModal.toggle()
            }) {
                Text("Show Modal")
            }
        }
        .sheet(isPresented: $isShowingModal) {
            NavigationView {
                ChildView(title: 1)
            }
            .onDisappear {
                print("Modal Dismissed")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)