gpt4 book ai didi

ios - 是否有 viewWillDisappear(_ :) or detect when a view is about to be removed? 的 SwiftUI 等效项

转载 作者:行者123 更新时间:2023-12-02 07:22:08 30 4
gpt4 key购买 nike

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

使用 onDisappear(perform:) 的作用类似于 viewDidDisappear(_:),并且该操作在另一个 View 出现后执行。

或者,我认为可以通过检测何时按下 default navigationBarBackButton 来解决上述问题。但我没有找到方法来检测这一点。

是否有任何解决方案可以在另一个 View 出现之前执行某些操作?

(我已经知道可以通过创建自定义导航后退按钮来关闭 View 来做到这一点)

最佳答案

这是适合我的方法,它不是纯 SwiftUI,但我认为值得发布

用法:

   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))
}
}

关于ios - 是否有 viewWillDisappear(_ :) or detect when a view is about to be removed? 的 SwiftUI 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59745663/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com