SwiftUI .onAppear,仅运行一次

时间:2020-08-15 07:58:05

标签: ios swift swiftui onappear

SwiftUI应用中,我的代码是这样的:

var body: some View {
    VStack {
        Spacer()
        ........
    }
    .onAppear {
      .... I want to have some code here ....
      .... to run when the view appears ....
    }
}

我的问题是我想在 .onAppear 块中运行一些代码,以便在应用显示在屏幕上,启动后或在后台运行一段时间后可以运行它。但似乎这段代码在应用程序启动时仅运行一次,以后再也不会运行。我想念什么吗?还是应该使用其他策略来获得想要的结果?

2 个答案:

答案 0 :(得分:4)

您必须在应用程序进入前台时观察该事件,然后使用@Published将其发布到ContentView。方法如下:

struct ContentView: View {

    @ObservedObject var observer = Observer()

    var body: some View {
        VStack {
            Spacer()
            //...
        }
        .onReceive(self.observer.$enteredForeground) { _ in
            print("App entered foreground!") // do stuff here
        }
    }
}

class Observer: ObservableObject {

    @Published var enteredForeground = true

    init() {
        if #available(iOS 13.0, *) {
            NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIScene.willEnterForegroundNotification, object: nil)
        } else {
            NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
        }
    }

    @objc func willEnterForeground() {
        enteredForeground.toggle()
    }
}

答案 1 :(得分:4)

如果您针对 iOS14 进行链接,那么您可以利用新的 scenePhase 概念:

@Environment(\.scenePhase) var scenePhase

如果注入此属性,您可以针对以下三种条件进行测试:

switch newPhase {
    case .inactive:
        print("inactive")
    case .active:
        print("active")
    case .background:
        print("background")
}

所以,一起来:

struct ContentView: View {
    @Environment(\.scenePhase) var scenePhase

    var body: some View {
        Text("Hello, World!")
            .onChange(of: scenePhase) { newPhase in
                switch newPhase {
                    case .inactive:
                        print("inactive")
                    case .active:
                        print("active")
                    case .background:
                        print("background")
                }
            }
    }
}