1

如果我有一个 SwiftUI 视图并将其放入后台(即在 iPhone 上点击一次主页按钮)然后再次重新打开它,我想触发一些操作。

我的第一个想法是利用

.onAppear{}

修饰符,但是,经过一些测试,这不适用于在后台后进入前台的视图。

似乎没有与 UIKit ViewWillAppear 等效的 SwiftUI。

我在想也许场景委托在这里很有用,因为它确实提供了以下功能:

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
}

但我不确定当视图从后台进入前景时,是否有一种有效的方法可以使用此函数来触发视图中的操作。

对此的任何想法将不胜感激。

4

2 回答 2

1

sceneWillEnterForeground 应该详细工作https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_foreground

或者,如果您只有关心前台操作的特定组件,您可以订阅通知中心,详情如下https://www.hackingwithswift.com/books/ios-swiftui/how-to-be-notified-when-your- swiftui-app-移动到后台

于 2020-07-23T02:29:28.807 回答
0

您可以通过使用此修饰符来实现它:

.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
            // your code
        }
于 2021-12-10T03:43:36.347 回答