如何解决SwiftUI .onAppear,仅运行一次
在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,name: UIApplication.willEnterForegroundNotification,object: nil)
}
}
@objc func willEnterForeground() {
enteredForeground.toggle()
}
}
,
如果您针对 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")
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。