我最近從使用 AppDelegate 遷移到僅使用 SwiftUI 應用程式生命周期。但是在某些情況下,當我的應用程式已經在后臺運行了很長一段時間(甚至可能被作業系統終止以釋放記憶體)時,似乎并沒有呼叫初始化方法。
@main
struct MyApp: App {
init() {
// Expected:
// This method is called whenever:
// 1. Application is launched (cold start)
// 2. Application is terminated due to memory, and user launches application again
// 3. Applicaiton is inactive, and becomes active again
}
var body: some Scene {
WindowGroup {
SplashView()
}
}
}
uj5u.com熱心網友回復:
更新:
當需要構建視圖時呼叫初始化程式。這可能有不同的原因。
包括:
- 視圖第一次初始化
- 狀態改變迫使視圖被重建
但也涉及到快取。所以你不應該依賴初始化器來更新資料。
/更新
在 SwiftUI 生命周期中,您希望對狀態更改做出反應:
@main
struct MyApp: App {
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup {
MyRootView()
}
.onChange(of: scenePhase) { phase in
if phase == .background {
// Perform cleanup when all scenes within
// MyApp go to the background.
}
}
}
}
參考:https : //developer.apple.com/documentation/swiftui/scenephase
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/421121.html
標籤:
上一篇:訪問structswift的資料
下一篇:如何快速回呼管理器類中的委托方法
