首页 > 解决方案 > 关闭模式视图时未调用 onDisappear

问题描述

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

未调用“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)")
        }
    }
}

输出是:

onAppear ChildView 1
onAppear ChildView 2
onDisappear ChildView 1

在此处输入图像描述

标签: iosswiftui

解决方案


如果您正在寻找在实际模式被解除时发生的逻辑,您将要在这里调用它,我打印出 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")
            }
        }
    }
}

推荐阅读