繁体   English   中英

SwiftUI.on出现,只运行一次

[英]SwiftUI .onAppear, only running once

SwiftUI应用程序中,我有这样的代码:

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

我的问题是我想在.onAppear块内运行一些代码,以便在应用程序出现在屏幕上、启动后或在后台运行一段时间后运行它。 但似乎这段代码只在应用程序启动时运行一次,之后再也不运行了。 我错过了什么吗? 或者我应该使用不同的策略来获得我想要的结果?

当应用程序进入前台并使用@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()
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

如果您要链接到 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")
                }
            }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM