的SwiftUI或检测何时将要删除视图

的SwiftUI或检测何时将要删除视图

本文介绍了是否有等效于viewWillDisappear(_ :)的SwiftUI或检测何时将要删除视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SwiftUI中,我试图找到一种方法,仅当使用默认的 navigationBackButton 时,才会检测到视图将被删除.然后执行一些操作.

In SwiftUI, I'm trying to find a way to detect that a view is about to be removed only when using the default navigationBackButton. Then perform some action.

使用 onDisappear(perform:)类似于 viewDidDisappear(_:),该操作将在另一个视图出现后执行.

Using onDisappear(perform:) acts like viewDidDisappear(_:), and the action performs after another view appears.

或者,我想通过检测何时按下默认 navigationBarBackButton 可以解决上述问题.但是我发现没有办法检测到它.

Or, I was thinking the above problem might be solved by detecting when the default navigationBarBackButton is pressed. But I've found no way to detect that.

在其他视图出现之前,是否有解决方案可以执行某些操作?

Is there any solution to perform some action before another view appears?

(我已经知道可以通过创建自定义导航后退按钮以关闭视图来实现此目的)

(I already know it is possible to do that by creating a custom navigation back button to dismiss a view)

推荐答案

这是对我有用的方法,它不是纯粹的SwiftUI,但我认为值得发布

Here is approach that works for me, it is not pure-SwiftUI but I assume worth posting

用法:

   SomeView()
   .onDisappear {
        print("x Default disappear")
    }
   .onWillDisappear { // << order does NOT matter
        print(">>> going to disappear")
    }

代码:

struct WillDisappearHandler: UIViewControllerRepresentable {
    func makeCoordinator() -> WillDisappearHandler.Coordinator {
        Coordinator(onWillDisappear: onWillDisappear)
    }

    let onWillDisappear: () -> Void

    func makeUIViewController(context: UIViewControllerRepresentableContext<WillDisappearHandler>) -> UIViewController {
        context.coordinator
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<WillDisappearHandler>) {
    }

    typealias UIViewControllerType = UIViewController

    class Coordinator: UIViewController {
        let onWillDisappear: () -> Void

        init(onWillDisappear: @escaping () -> Void) {
            self.onWillDisappear = onWillDisappear
            super.init(nibName: nil, bundle: nil)
        }

        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

        override func viewWillDisappear(_ animated: Bool) {
            super.viewWillDisappear(animated)
            onWillDisappear()
        }
    }
}

struct WillDisappearModifier: ViewModifier {
    let callback: () -> Void

    func body(content: Content) -> some View {
        content
            .background(WillDisappearHandler(onWillDisappear: callback))
    }
}

extension View {
    func onWillDisappear(_ perform: @escaping () -> Void) -> some View {
        self.modifier(WillDisappearModifier(callback: perform))
    }
}

这篇关于是否有等效于viewWillDisappear(_ :)的SwiftUI或检测何时将要删除视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 22:06