关闭模态视图时不调用 onDisappear [英] onDisappear not called when a modal View is dismissed

查看:26
本文介绍了关闭模态视图时不调用 onDisappear的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I rely on the SwiftUI's .onDisappear to perform some logic but it is not being called when the user dismisses a modally presented view with the swipe gesture. To reproduce

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

未调用ChildView 2"的 .onDisappear.

The .onDisappear of "ChildView 2" is not called.

要重现的示例代码

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

推荐答案

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

If you're looking for logic to occur when the actual modal is dismissed, you're going to want to call that here, where I print out 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")
            }
        }
    }
}

这篇关于关闭模态视图时不调用 onDisappear的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆