Mic*_*hel 8 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 ....
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我想在.onAppear块中运行一些代码,以便在应用程序出现在屏幕上、启动后或在后台一段时间后运行。但似乎这段代码只在应用启动时运行一次,之后再也不运行了。我错过了什么吗?或者我应该使用不同的策略来获得我想要的结果?
Bib*_*cob 10
当应用程序进入前台时,您必须观察该事件并将其发布@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)
}
}
Run Code Online (Sandbox Code Playgroud)
如果您要针对 iOS14 进行链接,那么您可以利用新scenePhase概念:
@Environment(\.scenePhase) var scenePhase
Run Code Online (Sandbox Code Playgroud)
如果注入此属性,您可以针对以下三个条件进行测试:
switch newPhase {
case .inactive:
print("inactive")
case .active:
print("active")
case .background:
print("background")
}
Run Code Online (Sandbox Code Playgroud)
所以,一起来:
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")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3311 次 |
| 最近记录: |