ios - SwiftUI .onAppear,只运行一次

标签 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 block 内运行一些代码,以便在应用程序出现在屏幕上、启动后或在后台运行一段时间后运行它。但似乎这段代码只在应用程序启动时运行一次,之后再也不运行了。我错过了什么吗?或者我应该使用不同的策略来获得我想要的结果?

最佳答案

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

关于ios - SwiftUI .onAppear,只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63423845/

相关文章:

php - 如何快速从json数据中获取特定值

ios - 在 RxSwift 中点击按钮不会在平面 map 范围内调用 Moya 网络请求

swift - '? :'表达式中的结果值具有不匹配的类型 'some View'和 '...'

button - 如何在 SwiftUI 中使一组按钮宽度相同

SwiftUI:为什么这个ScrollView的内容放错了地方?

ios - DateFormatting结果为null

ios - 屏幕锁定 (IOS) 后,React native Webview 被阻止

swift - 绑定(bind)的 property/$property 语法是什么?

ios - 在 UICollectionView 中创建 2 x 2 水平网格?

iphone - 在 iPhone 中使用 UIPanGesture 旋转 UIView 的框架增加减少