gpt4 book ai didi

ios - SwiftUI .onAppear,只运行一次

转载 作者:行者123 更新时间:2023-12-03 15:27:19 26 4
gpt4 key购买 nike

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/

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